加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Sklearn将字符串类标签更改为int

发布时间:2020-12-20 11:57:58 所属栏目:Python 来源:网络整理
导读:我有一个pandas数据帧,我正在尝试将字符串表示的给定列中的值更改为整数.例如: df = index fruit quantity price 0 apple 5 0.99 1 apple 2 0.99 2 orange 4 0.89 4 banana 1 1.64 ... 10023 kiwi 10 0.92 我想看看: df = index fruit quantity price 0 1
我有一个pandas数据帧,我正在尝试将字符串表示的给定列中的值更改为整数.例如:

df = index    fruit   quantity   price 
         0    apple          5    0.99
         1    apple          2    0.99
         2   orange          4    0.89
         4   banana          1    1.64
       ...
     10023     kiwi         10    0.92

我想看看:

df = index    fruit   quantity   price 
         0        1          5    0.99
         1        1          2    0.99
         2        2          4    0.89
         4        3          1    1.64
       ...
     10023        5         10    0.92

我可以这样做

df["fruit"] = df["fruit"].map({"apple": 1,"orange": 2,...})

如果我有一个小的列表要改变,这是有效的,但我正在看一个有500多个不同标签的专栏.有没有办法将其从字符串更改为int?

解决方法

使用 factorize然后根据需要转换为 categorical

df.fruit = pd.factorize(df.fruit)[0]
print (df)
   fruit  quantity  price
0      0         5   0.99
1      0         2   0.99
2      1         4   0.89
3      2         1   1.64
4      3        10   0.92
df.fruit = pd.Categorical(pd.factorize(df.fruit)[0])
print (df)
  fruit  quantity  price
0     0         5   0.99
1     0         2   0.99
2     1         4   0.89
3     2         1   1.64
4     3        10   0.92

print (df.dtypes)
fruit       category
quantity       int64
price        float64
dtype: object

如果需要从1开始计数:

df.fruit = pd.Categorical(pd.factorize(df.fruit)[0] + 1)
print (df)
  fruit  quantity  price
0     1         5   0.99
1     1         2   0.99
2     2         4   0.89
3     3         1   1.64
4     4        10   0.92

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读