【问题标题】:Convert object data type column to integer error将对象数据类型列转换为整数错误
【发布时间】:2021-02-15 13:13:55
【问题描述】:

我有一个 df 列,我想只过滤负值或正值,

当我尝试以下代码时:

df.loc[df['values'] > 0]

我得到错误

`TypeError: '>' not supported between instances of 'str' and 'int'

我尝试将值列的对象数据类型转换为整数:

df['values'].astype(str).astype(int) 

我收到以下错误:ValueError: invalid literal for int() with base 10: '3.69'

谢谢!

如何正确转换以便正确过滤?谢谢!

【问题讨论】:

  • 将其转换为浮点数(3.69 为浮点数)

标签: python python-3.x pandas data-science


【解决方案1】:

如果要将其转换为 int,则应使用 apply 函数:

df = df.assign(values = lambda x: x['values'].apply(lambda s: int(s))) 

【讨论】:

    【解决方案2】:

    您需要将其转换为 float dtype,因为 3.69 是小数(因此是 float)。 int 数据类型只能是非十进制数字(例如 1、2、4、100、900)。试试这个:

    df.loc[df['values'].astype(float) > 0]
    

    【讨论】:

      猜你喜欢
      • 2020-10-04
      • 2010-11-10
      • 2018-06-25
      • 1970-01-01
      • 2013-04-24
      • 2018-12-09
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      相关资源
      最近更新 更多