【发布时间】:2013-03-21 08:35:11
【问题描述】:
在 pandas 中,如何将 DataFrame 的列转换为 dtype 对象?
或者更好的是,成为一个因素? (对于会说 R 的人,在 Python 中,我该如何as.factor()?)
另外,pandas.Factor 和 pandas.Categorical 有什么区别?
【问题讨论】:
在 pandas 中,如何将 DataFrame 的列转换为 dtype 对象?
或者更好的是,成为一个因素? (对于会说 R 的人,在 Python 中,我该如何as.factor()?)
另外,pandas.Factor 和 pandas.Categorical 有什么区别?
【问题讨论】:
您可以使用astype 方法投射一个系列(一列):
df['col_name'] = df['col_name'].astype(object)
或者整个DataFrame:
df = df.astype(object)
Since version 0.15, you can use the category datatype 在系列/列中:
df['col_name'] = df['col_name'].astype('category')
注意:pd.Factor 已被弃用并已被删除以支持pd.Categorical。
【讨论】:
data['engagement'].astype(object)...如果它们已经是浮动的,为什么要更改为对象?
还有 pd.factorize 函数可以使用:
# use the df data from @herrfz
In [150]: pd.factorize(df.b)
Out[150]: (array([0, 1, 0, 1, 2]), array(['yes', 'no', 'absent'], dtype=object))
In [152]: df['c'] = pd.factorize(df.b)[0]
In [153]: df
Out[153]:
a b c
0 1 yes 0
1 2 no 1
2 3 yes 0
3 4 no 1
4 5 absent 2
【讨论】:
据我所知,Factor 和 Categorical 是相同的。我认为它最初被称为因子,然后改为分类。要转换为分类,也许您可以使用pandas.Categorical.from_array,如下所示:
In [27]: df = pd.DataFrame({'a' : [1, 2, 3, 4, 5], 'b' : ['yes', 'no', 'yes', 'no', 'absent']})
In [28]: df
Out[28]:
a b
0 1 yes
1 2 no
2 3 yes
3 4 no
4 5 absent
In [29]: df['c'] = pd.Categorical.from_array(df.b).labels
In [30]: df
Out[30]:
a b c
0 1 yes 2
1 2 no 1
2 3 yes 2
3 4 no 1
4 5 absent 0
【讨论】:
pd.Categorical(df.b).codes