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

smc*_*mci 8 pandas categorical-data

我可以将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版本).

smc*_*mci 7

我发现0.15之前的熊猫唯一的解决方法如下:

  • 必须将列转换为分类器的分类,但是numpy会立即将级别强制转换为int,从而丢失因子信息
  • 所以将因子存储在数据帧外的全局变量中

.

train_LocationNFactor = pd.Categorical.from_array(train['LocationNormalized']) # default order: alphabetical

train['LocationNFactor'] = train_LocationNFactor.labels # insert in dataframe
Run Code Online (Sandbox Code Playgroud)

[更新:pandas 0.15+为分类增加了不错的支持 ]