【问题标题】:How to convert numbers into category in a column in pandas如何将数字转换为熊猫列中的类别
【发布时间】:2021-01-13 02:23:09
【问题描述】:

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

这是我想要实现的目标:

万分感谢!

【问题讨论】:

  • pd.cut(df['A'],bins=[0,20.0,df['A'].max()],labels=['小于 20','大于 20 '])

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


【解决方案1】:

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

【讨论】:

  • 你是个天才!兄弟!
  • 很高兴为您提供帮助。请不要忘记也为答案投票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-25
  • 2019-10-12
  • 2021-08-18
  • 2019-07-29
  • 2018-05-15
相关资源
最近更新 更多