【问题标题】:AttributeError: 'NoneType' object has no attribute 'lstrip'AttributeError:“NoneType”对象没有属性“lstrip”
【发布时间】:2016-09-05 19:09:21
【问题描述】:

我在 Pandas 中有一个数据框,当我尝试删除它的某些字符时出现以下错误:

AttributeError: 'NoneType' 对象没有属性 'lstrip'

我首先删除了所有缺失值或空值:

df_sample1['counties'].fillna('missing')

检查它,我看到很多不干净的数据,混合了实际数据(County 1、Count 2...Count n)以及乱码($%ZYC 2)。

为了进一步清理,我运行了以下代码:

df_sample1['counties'] = df_sample1['counties'].map(lambda x: x.lstrip('+%=/-#$;!\(!\&=&:%;').rstrip('1234567890+%=/-#$;!\(!\&=&:%;'))
df_sample1[:10]

这会产生“NoneType”错误。 我挖了一点,在 Pandas 文档中,有一些关于跳过缺失值的提示。

if df_sample1['counties'] is None:
    pass 
else:
   df_sample1['counties'].map(lambda x: x.lstrip('+%=/-#$;!\(!\&=&:%;').rstrip('1234567890+%=/-#$;!\(!\&=&:%;'))

这仍然会产生上面提到的 NoneType 错误。有人能指出我做错了什么吗?

【问题讨论】:

  • 您需要在您的lambda 中包含if
  • 如果你这样调用fillna,它只是返回一个副本,不会改变原来的df。试试df_sample1['counties'].fillna('missing', inplace=True)
  • 参见the docs 中的参数na_action

标签: python pandas


【解决方案1】:

您可以“跳过”None,方法是在进行剥离之前检查 x 是否为真...

df_sample1['counties'].map(lambda x: x and x.lstrip('+%=/-#$;!\(!\&=&:%;').rstrip('1234567890+%=/-#$;!\(!\&=&:%;'))

这可能会在数据框中留下一些None(在它们之前的相同位置),但转换仍应适用于字符串。

【讨论】:

    【解决方案2】:

    如果你正在处理文本数据,为什么不先用空字符串填充 None 类型的数据?

    df_sample1['counties'].fillna("", inplace=True)
    

    【讨论】:

      【解决方案3】:

      我怀疑您的问题是,当您填写缺失值时,您没有就地完成。这可以通过以下方式解决:

      df_sample1['counties'].fillna('missing', inplace=True)
      

      或者,在应用pandas.Series.map 时,您可以使用参数na_action 将这些条目保留为None

      df_sample1['counties'] = df_sample1['counties'].map(lambda x: ..., na_action='ignore')
      

      【讨论】:

        猜你喜欢
        • 2019-12-28
        • 2019-01-01
        • 2021-12-26
        • 2019-07-23
        • 2018-05-13
        • 2020-09-07
        • 2017-05-03
        • 2023-03-16
        • 2018-07-14
        相关资源
        最近更新 更多