问题描述
假设我有一个包含以下国家/地区的数据框:
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 函数可以将国家/地区转换为one-hot encodings".但是,我希望将它们转换为索引,这样我就会得到 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 中使用因子"更容易做到这一点,所以我希望 Pandas 有类似的东西.
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:将类别转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!