【问题标题】:Not supported between instances of str and int在 str 和 int 的实例之间不支持
【发布时间】:2019-09-10 16:50:33
【问题描述】:

我有这个代码

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

为我工作。但是当我使用

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

弹出一条错误消息

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

我想让'high' 用于高于 30 的值,'low' 用于同一 pandas 列上的低于 30 的值。

【问题讨论】:

  • 你能分享你的数据框吗?
  • Python 3 中不再允许不同数据类型之间的比较。这就是您的错误似乎所说的。也许您可以在您的问题中添加更多代码?
  • 您先将一半数据设置为字符串(即'low'),然后将这些字符串与数字30进行比较。不允许此操作...
  • ['A'] 包含整数和浮点数,但希望将它们分组为值 30 的高低。它实际上是我正在处理的机器学习(分类)任务
  • 按照人们的要求,您应该向我们展示您的数据框/数据的样本

标签: python pandas


【解决方案1】:

使用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

【讨论】:

    【解决方案2】:

    当你写下这一行时:

    data['A'].loc[data['A']&gt;30] = 'high'

    您将A 列转换为object 类型的列,其中包含intstr

    当你写第二行时

    data['A'].loc[data['A']&lt;30] = 'low'

    pandas 遍历整个列(包括已将其值更新为 'high'&gt;30

    最好的方法是使用 gmds 提到的pd.cut

    您也可以创建第二列,然后将其放在最后。

    data['B'] = 'low'
    data.loc[data.A>30, 'B'] = 'high'
    data['A'] = data['B']
    data.drop(columns=['B'], inplace=True)
    

    不是最优雅的解决方案,但它有效

    【讨论】:

      猜你喜欢
      • 2020-05-19
      • 2021-08-10
      • 2019-11-18
      • 1970-01-01
      • 2018-02-23
      • 2020-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多