如何将数字转换为熊猫列中的类别

时间:2020-09-27 08:15:00

标签: python python-3.x pandas type-conversion

如何在列名“ A”中将整数转换为类别“小于或等于20”和“大于20”?

这是我要实现的目标:

enter image description here

成千上万的感谢!

1 个答案:

答案 0 :(得分:0)

您可以使用numpy.select

In [744]: df
Out[744]: 
    A
0  12
1  23
2  18
3  39
4  15

In [744]: import numpy as np
In [745]: conditions = [df.A.le(20), df.A.gt(20)]

In [746]: choices = ['Less than or equal to 20', 'Greater than 20']

In [749]: df['categorical_A'] = np.select(conditions, choices)

In [750]: df
Out[750]: 
    A             categorical_A
0  12  Less than or equal to 20
1  23           Greater than 20
2  18  Less than or equal to 20
3  39           Greater than 20
4  15  Less than or equal to 20