gpt4 book ai didi

python - 属性错误: 'NoneType' object has no attribute 'lstrip'

转载 作者:行者123 更新时间:2023-11-30 22:56:06 24 4
gpt4 key购买 nike

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

AttributeError: 'NoneType' object has no attribute '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 错误。有人可以指出我做错了什么吗?

最佳答案

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

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

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

关于python - 属性错误: 'NoneType' object has no attribute 'lstrip' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37144736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com