![](/img/trans.png)
[英]How to solve the AttributeError:'list' object has no attribute 'astype'?
[英]How do I fix AttributeError: “list” attribute has no attribute 'astype' in list-comprehensions?
基本上我正在尝试在列表推导中使用 contains 方法。 但我在这样做时遇到了问题。
我已经尝试过使用
[x.apply(', '.join).str.contains('|'.join(searchfor)) for x in losdata["Crime_Type"] ]
在代码中。 它不起作用。
searchfor = ["BURGALORY","ROBBERY","THEFT","STOLEN",
"SNATCHING","STEALING","FELONY","PICKPOCKET","BUNCO","EMBEZZLEMENT"]
losdata["Crime_Type"] = ["Burglary" if(x.astype(str).str.contains('|'.join(searchfor)))
else "TBC"
for x in losdata["Crime_Type"]
]
print(losdata.head())
losdata['Crime_Type'] 是一个object数据类型。 losdata 是 pandas dataframe。 我期望的是,对于 losdata['Crime_Type'] 中的每个 object,我应该能够在列表推导中使用 contains()。 我见过像这样的解决方案
df[df['A'].str.contains('a')==True]
'A' 只是任何列名。 但我还没有想出如何在我的情况下解决它。
我找到了另一种编码方式。
losdata["Crime_Type"] = ["BURGLARY" if(x.find("BURGALORY")>0 or x.find("ROBBERY")>0 or x.find("THEFT")>0 or x.find("STOLEN")>0 or x.find("SNATCHING")>0 or x.find("STEALING")>0)
else "OTHER"
for x in losdata['Crime_Type']
]
print(losdata.head())
它有效,但仍在等待更有效的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.