相关疑难解决方法(0)

如何从字符串列生成分类的pandas DataFrame列?

我可以将pandas字符串列转换为Categorical,但是当我尝试将其作为新的DataFrame列插入时,它似乎被转换回系列str:

train['LocationNFactor'] = pd.Categorical.from_array(train['LocationNormalized'])

>>> type(pd.Categorical.from_array(train['LocationNormalized']))
<class 'pandas.core.categorical.Categorical'>
# however it got converted back to...
>>> type(train['LocationNFactor'][2])
<type 'str'>
>>> train['LocationNFactor'][2]
'Hampshire'
Run Code Online (Sandbox Code Playgroud)

猜测这是因为分类不映射到任何numpy dtype; 所以我必须将它转换为某种int类型,从而失去因子标签< - >级别关联?存储级别< - >标签关联并保留转换回来的能力的最优雅的解决方法是什么?(只是存储像这里的dict ,并在需要时手动转换?)我认为Categorical仍然不是DataFrame的第一类数据类型,不像R.

(使用pandas 0.10.1,numpy 1.6.2,python 2.7.3 - 所有内容的最新macports版本).

pandas categorical-data

8
推荐指数
1
解决办法
9367
查看次数

标签 统计

categorical-data ×1

pandas ×1