首页 > 解决方案 > 在 str 和 int 的实例之间不支持

问题描述

我有这个代码

data['A'].loc[data['A']>30] = 'high' 

为我工作。但是,当我使用

data['A'].loc[data['A']<30] = 'low' 

弹出错误信息

'<' not supported between instances of 'str' and 'int'

我希望在同一熊猫列上具有'high'高于 30的值和低于 30 的值。'low'

标签: pythonpandas

解决方案


代替手动方法,使用pd.cut

pd.cut(data['A'], [float('-inf'), 30, float('inf')], labels=['low', 'high'])

例子:

s = pd.Series([-10, 40, 70, 60, 20])
pd.cut(s, [float('-inf'), 30, float('inf')], labels=['low', 'high'])

输出:

0     low
1    high
2    high
3    high
4     low

推荐阅读