【发布时间】: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。