在pandas中,如何将DataFrame的列转换为dtype对象?或者更好的是,成为一个因素?(对于那些使用Python语言使用R的人来说,如何使用as.factor()?)
另外,pandas.Factor和pandas.Categorical之间的区别是什么
发布于 2013-03-31 05:54:21
您可以使用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__。
发布于 2013-11-18 23:35:08
还可以使用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发布于 2013-03-31 06:04:14
据我所知,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 0https://stackoverflow.com/questions/15723628
复制相似问题