首页 文章

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

提问于
浏览
1

我在Pandas中有一个数据框,当我尝试剥离某些字符时,它会给我以下错误:

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

我开始删除任何缺失或空值:

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

检查一下,我看到很多不干净的数据,实际数据(县1,计数2 ......计数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错误 . 有人能指出我做错了什么吗?

3 回答

  • 1

    你可以"skip" None 检查是否 x 在进行剥离之前是真的...

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

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

  • 1

    如果您正在使用文本数据,为什么不首先使用空字符串填充无类型数据?

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

    我怀疑你的问题是,当你填写缺失的值时,你没有在原地进行 . 这可以通过以下方式解决:

    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')
    

相关问题