Sklearn将字符串类标签更改为in

2024-05-19 01:45:43 发布

您现在位置: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          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多个不同标签的列。有没有办法把这个从string改成int


Tags: 数据字符串mapapplepandasdfindex整数
2条回答

使用^{},然后根据需要转换为^{}

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

您可以使用factorize方法:

In [13]: df['fruit'] = pd.factorize(df['fruit'])[0].astype(np.uint16)

In [14]: df
Out[14]:
   index  fruit  quantity  price
0      0      0         5   0.99
1      1      0         2   0.99
2      2      1         4   0.89
3      4      2         1   1.64
4  10023      3        10   0.92

In [15]: df.dtypes
Out[15]:
index         int64
fruit        uint16
quantity      int64
price       float64
dtype: object

或者你可以这样做:

In [21]: df['fruit'] = df.fruit.astype('category').cat.codes

In [22]: df
Out[22]:
   index  fruit  quantity  price
0      0      0         5   0.99
1      1      0         2   0.99
2      2      3         4   0.89
3      4      1         1   1.64
4  10023      2        10   0.92

In [23]: df.dtypes
Out[23]:
index         int64
fruit          int8
quantity      int64
price       float64
dtype: object

相关问题 更多 >

    热门问题