假设我有一个包含国家/地区的数据框,如下所示:
cc | temp
US | 37.0
CA | 12.0
US | 35.0
AU | 20.0
我知道有一个 pd.get_dummies 函数可以将国家/地区转换为“one-hot 编码”。但是,我希望将它们转换为索引,这样我就会得到
cc_index = [1,2,1,3]
。
我假设有一种比使用 get_dummies 和 numpy where 子句更快的方法,如下所示:
[np.where(x) for x in df.cc.get_dummies().values]
在 R 中使用“因子”更容易做到这一点,所以我希望 pandas 也有类似的东西。
首先,更改列的类型:
df.cc = pd.Categorical(df.cc)
现在数据看起来很相似,但是是分类存储的。要捕获类别代码:
df['code'] = df.cc.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 而只是获取代码:
df.cc.astype('category').codes
或者使用分类列作为索引:
df2 = pd.DataFrame(df.temp)
df2.index = pd.CategoricalIndex(df.cc)
pd.factorize
。
请注意,此解决方案与
pd.Categorical
不同,不会按字母顺序排序。因此第一个国家将被指定为0
。如果你想从1
开始,你可以添加一个常数:
df['code'] = pd.factorize(df['cc'])[0] + 1
print(df)
cc temp code
0 US 37.0 1
1 CA 12.0 2
2 US 35.0 1
3 AU 20.0 3
如果您想按字母顺序排序,请指定
sort=True
:
df['code'] = pd.factorize(df['cc'], sort=True)[0] + 1
sklearn
库,则可以使用 LabelEncoder
。与 pd.Categorical
一样,输入字符串在编码之前按字母顺序排序。
from sklearn.preprocessing import LabelEncoder
LE = LabelEncoder()
df['code'] = LE.fit_transform(df['cc'])
print(df)
cc temp code
0 US 37.0 2
1 CA 12.0 1
2 US 35.0 2
3 AU 20.0 0
一行代码:
df[['cc']] = df[['cc']].apply(lambda col:pd.Categorical(col).codes)
如果您有
list_of_columns
,这也适用:
df[list_of_columns] = df[list_of_columns].apply(lambda col:pd.Categorical(col).codes)
此外,如果您想保留
NaN
值,您可以应用替换:
df[['cc']] = df[['cc']].apply(lambda col:pd.Categorical(col).codes).replace(-1,np.nan)
试试这个,根据频率转换为数字(高频 - 高数字):
labels = df[col].value_counts(ascending=True).index.tolist()
codes = range(1,len(labels)+1)
df[col].replace(labels,codes,inplace=True)
将任何列更改为数字。它不会创建新列,而只是用数字数据替换值。
def characters_to_numb(*args):
for arg in args:
df[arg] = pd.Categorical(df[arg])
df[arg] = df[arg].cat.codes
return df