我在 Python 中运行以下命令时遇到 AttributeError:
start = datetime.now()
df_no_dup["tag_count"] = df_no_dup["Tags"].apply(lambda text: len(text.split(" ")))
# adding a new feature number of tags per question
print("Time taken to run this cell :", datetime.now() - start)
df_no_dup.head()
错误信息如下:
AttributeError: 'NoneType' object has no attribute 'split'
我正在尝试使用 apply 函数计算每个问题的标签数量,但似乎可能存在“标签”列包含 NoneType 对象的情况。如何修改代码来处理此类情况并避免 AttributeError?
任何解决此问题的帮助将不胜感激。
如果你确定你处理的值都是字符串那么你就可以做出判断了
from datetime import datetime
start = datetime.now()
df_no_dup["tag_count"] = df_no_dup["Tags"].apply(lambda text: len(text.split(" ") if text else 0))
# adding a new feature number of tags per question
print("Time taken to run this cell :", datetime.now() - start)
df_no_dup.head()
df_no_dup["Tags"] 没有值。只需添加一个 if 子句来保护它即可。
start = datetime.now()
if df_no_dup["Tags"] is not None:
df_no_dup["tag_count"] = df_no_dup["Tags"].apply(lambda text: len(text.split(" ")))
# adding a new feature number of tags per question
print("Time taken to run this cell :", datetime.now() - start)
df_no_dup.head()