我第一次和熊猫合作。我有一篇包含调查回复的专栏文章,可以采用“强烈同意”、“同意”、“不同意”、“强烈反对”和“两者都不同意”的价值观。
这是该列的describe()和value_counts()的输出:
count 4996
unique 5
top Agree
freq 1745
dtype: object
Agree 1745
Strongly agree 926
Strongly disagree 918
Disagree 793
Neither 614
dtype: int64我想对这个问题和总分做一个线性回归。但是,考虑到列本身是有序的,我有一种感觉,我应该首先将该列转换为一个类别变量。这是正确的吗?如果是的话,我该怎么做呢?
我试过这个:
df.EasyToUseQuestionFactor = pd.Categorical.from_array(df.EasyToUseQuestion)
print df.EasyToUseQuestionFactor这产生的输出看起来似乎是正确的,但似乎类别的顺序是错误的。有什么方法我可以指定订单吗?我甚至需要指定订单吗?
这是我现在剩下的代码:
df = pd.read_csv('./data/responses.csv')
lm1 = ols('OverallScore ~ EasyToUseQuestion', data).fit()
print lm1.rsquared 发布于 2014-09-19 17:42:01
是的,你应该把它转换成分类数据,这样就可以了。
likert_scale = {'strongly agree':2, 'agree':1, 'neither':0, 'disagree':-1, 'strongly disagree':-2}
df['categorical_data'] = df.EasyToUseQuestion.apply(lambda x: likert_scale[x])发布于 2018-12-01 16:35:37
现在有两种方法。您的列的可读性更强,使用的内存也更少。由于它将是一个分类类型,您仍然可以排序这些值。
首先,我喜欢的是:
df['grades'].astype('category')astype过去接受categories参数,但它不是送礼。因此,如果您想按非词典顺序排序您的类别,或者希望您的数据中没有额外的类别,您必须使用下面的解决方案。
此建议来自于文档
In [26]: from pandas.api.types import CategoricalDtype
In [27]: s = pd.Series(["a", "b", "c", "a"])
In [28]: cat_type = CategoricalDtype(categories=["b", "c", "d"],
....: ordered=True)
In [29]: s_cat = s.astype(cat_type)额外提示:从带有df.colname.unique()的列中获取所有现有值。
发布于 2021-03-18 01:05:19
pandas.factorize()可以获得数组的数字表示形式。
因式分解既可以作为顶级函数pandas.factorize(),也可以作为方法Series.factorize()和Index.factorize()使用。
import pandas as pd
df = pd.DataFrame({'answer' : ['strongly agree', 'strongly agree', 'agree', 'neither', 'disagree', 'strongly disagree']})
# df['category'] = pd.factorize(df['answer'])[0]
df['category'] = df['answer'].factorize()[0]# print(df)
answer category
0 strongly agree 0
1 strongly agree 0
2 agree 1
3 neither 2
4 disagree 3
5 strongly disagree 4https://stackoverflow.com/questions/25938557
复制相似问题