pandas :将类别转换为数字 [英] Pandas: convert categories to numbers

查看:83
本文介绍了 pandas :将类别转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含以下国家的数据框:

Suppose I have a dataframe with countries that goes as:

cc | temp
US | 37.0
CA | 12.0
US | 35.0
AU | 20.0

我知道有一个pd.get_dummies函数可以将国家/地区转换为一次性编码".但是,我希望将它们转换为索引,这样我将得到cc_index = [1,2,1,3].

I know that there is a pd.get_dummies function to convert the countries to 'one-hot encodings'. However, I wish to convert them to indices instead such that I will get cc_index = [1,2,1,3] instead.

我假设有一种比使用get_dummies和numpy where子句更快的方法,如下所示:

I'm assuming that there is a faster way than using the get_dummies along with a numpy where clause as shown below:

[np.where(x) for x in df.cc.get_dummies().values]

这在R中使用因素"更容易些,所以我希望熊猫也有类似的东西.

This is somewhat easier to do in R using 'factors' so I'm hoping pandas has something similar.

推荐答案

首先,更改列的类型:

df.cc = pd.Categorical(df.cc)

现在,数据看起来很相似,但是是按类别存储的.要捕获类别代码:

Now the data look similar but are stored categorically. To capture the category codes:

df['code'] = df.cc.cat.codes

现在您拥有:

   cc  temp  code
0  US  37.0     2
1  CA  12.0     1
2  US  35.0     2
3  AU  20.0     0

如果您不想修改DataFrame,而只需获取代码:

If you don't want to modify your DataFrame but simply get the codes:

df.cc.astype('category').cat.codes

或使用分类列作为索引:

Or use the categorical column as an index:

df2 = pd.DataFrame(df.temp)
df2.index = pd.CategoricalIndex(df.cc)

这篇关于 pandas :将类别转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆