Search code examples
pythonpandaslist-comprehensioncontains

How do I fix AttributeError: "list" attribute has no attribute 'astype' in list-comprehensions?


Basically I am trying to use contains method inside list comprehensions. But I am facing a problem doing this.

I've already tried using

[x.apply(', '.join).str.contains('|'.join(searchfor)) for x in losdata["Crime_Type"] ]

in the code. It doesn't work.

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'] is an object data-type. losdata is a pandas dataframe. What I expect is that for every object in losdata['Crime_Type'], I should be able to use contains() inside list comprehensions. I have seen solutions like

df[df['A'].str.contains('a')==True]

'A' is just any column name. But I haven't figured how to fix it in my case.


Solution

  • I found another way to code this.

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

    It works but still waiting for more effective way.