Pandas:将类别转换为数字

Pandas: convert categories to numbers

假设我有一个包含国家/地区的数据框:

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]

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

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

这在 R 中使用 'factors' 更容易做到,所以我希望 pandas 有类似的东西。

首先,更改列的类型:

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

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

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 而只是获取代码:

df.cc.astype('category').cat.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 library you can use 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

将任何列更改为数字。它不会创建新列,而只是用数值数据替换值。

def characters_to_numb(*args): for arg in args: df[arg] = pd.Categorical(df[arg]) df[arg] = df[arg].cat.codes return df

试试这个,根据频率转换为数字(高频 - 高数字):

labels = df[col].value_counts(ascending=True).index.tolist()
codes = range(1,len(labels)+1)
df[col].replace(labels,codes,inplace=True)

一行代码:

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)