Pandas:将类别转换为数字

wkyowqbh  于 2023-03-21  发布在  其他
关注(0)|答案(6)|浏览(135)

假设我有一个国家的数据框,如下所示:

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

我知道有一个pd.get_dummies函数可以将国家/地区转换为“独热编码”。但是,我希望将它们转换为索引,这样我将得到cc_index = [1,2,1,3]
我假设有一种比使用get_dummies沿着numpy where子句更快的方法,如下所示:
[np.where(x) for x in df.cc.get_dummies().values]
这在R中使用'factors'更容易做到,所以我希望pandas也有类似的东西。

raogr8fs

raogr8fs1#

首先,更改列的类型:

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)
uklbhaso

uklbhaso2#

如果只想将序列转换为整数标识符,可以使用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
k4aesqcs

k4aesqcs3#

如果你使用的是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
ahy6op9u

ahy6op9u4#

单行代码:

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)
de90aj5v

de90aj5v5#

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

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

kxkpmulp6#

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

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

相关问题