【问题标题】:Pandas Function getting error comparing floating number and integerPandas函数比较浮点数和整数时出错
【发布时间】:2021-09-30 15:41:03
【问题描述】:

我正在使用 Pandas 分析一个数据集,其中包含一个名为“Age on Intake”(浮点数)的列。我一直在尝试使用我编写的函数将数据进一步分类到几个小的年龄桶中。但是,我不断收到错误 "'"。请问我该如何解决这个问题?

我的功能:

def convert_age(num):
    
    if num <=7:
        return "0-7 days"
    elif num <= 21:
        return "1-3 weeks"
    elif num <= 42:
        return "3-6 weeks"
    elif num <= 84:
        return "7-12 weeks"
    elif num <= 168:
        return "12 weeks - 6 months"
    elif num <= 365:
        return "6-12 months"
    elif num <= 730:
        return "1-2 years"
    elif num <= 1095:
        return "2-3 years"
    else:
        return "3+ years"
   
df['Age on Intake'] = df['Age on Intake'].apply(convert_age)

df['Age on Intake'] 列包含浮点数:

0          95.0
1        1096.0
2         111.0
3         111.0
4         397.0
          ...  
21474       NaN
21475       NaN
21476     365.0
21477     699.0
21478      61.0
Name: Age on Intake, Length: 21479, dtype: float64

我收到的错误消息:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-31-ca12621d6b19> in <module>
     22         return "3+ years"
     23 
---> 24 df['Age on Intake'] = df['Age on Intake'].apply(convert_age)
     25 
     26 

/opt/anaconda3/lib/python3.8/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
   4198             else:
   4199                 values = self.astype(object)._values
-> 4200                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   4201 
   4202         if len(mapped) and isinstance(mapped[0], Series):

pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()

<ipython-input-31-ca12621d6b19> in convert_age(num)
      3 def convert_age(num):
      4 
----> 5     if num <=7:
      6         return "0-7 days"
      7     elif num <= 21:

TypeError: '<=' not supported between instances of 'str' and 'int'

【问题讨论】:

  • 请始终将数据和代码作为代码而不是屏幕截图发布。还包括您的数据样本和完整的错误回溯。
  • 感谢@not_speshal 的提示。我第一次发帖,刚刚编辑过
  • 嗯,鉴于您的系列显示dtype: float64,它确实应该有效。不过,有更好的方法可以使用pd.cut 对这些数据进行分类。你确定你还没有.apply(convert_age) 到那个列,这会使其成为字符串值,然后你不小心再次尝试调用该函数
  • 我建议您通过在函数中添加 try except 语句来调试它,如果有错误则打印 num 的值。然后,您可以找到它失败的值。
  • @ALollz 哇,谢谢!确实是因为我在修改代码以添加另一行“elif”语句后再次调用了该函数。(一个nooby的斗争)。非常感谢大家的意见!!

标签: python pandas dataframe function


【解决方案1】:

您的convert_age 中的num 参数似乎接收到一个字符串而不是一个int 值。尝试将其转换为 int,或忽略 int 以外的传入值。 考虑添加类似的内容。

try:
    converted_num = int(num)  # Trying to convert to int.
    # your code goes here
except ValueError:
    # We got an error while converting.
    pass

【讨论】:

    【解决方案2】:

    不直接回答问题(这个问题确实是类型问题,可以用astype解决),但你可以用pandas.cut替换你不友好的函数:

    import numpy as np
    import pandas as pd
    
    ages = {0: '0-7 days',
            7: '1-3 weeks',
            21: '3-6 weeks',
            42: '7-12 weeks',
            84: '12 weeks - 6 months',
            168: '6-12 months',
            365: '1-2 years',
            730: '2-3 years',
            1095: '3+ years'}
    
    pd.cut(df['Age on Intake'].astype(float),
           bins=list(ages.keys())+[np.inf],
           labels=ages.values(),
          )
    

    【讨论】:

    • 非常有帮助!以前不知道这件事。谢谢
    猜你喜欢
    • 2015-01-20
    • 2011-04-19
    • 2012-05-13
    • 1970-01-01
    • 2016-05-24
    • 2016-02-08
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多