首页 > 解决方案 > 如何将数字转换为熊猫列中的类别

问题描述

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

这是我想要实现的目标:

在此处输入图像描述

万分感谢!

标签: pythonpython-3.xpandastype-conversion

解决方案


您可以使用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

推荐阅读