Reputation: 367
Goal: I have this dataframe where I want to see if a "Country" belongs to "Another Country's Neighbors" list:
Country AnotherCountry AnotherCountryNeighbors
A X [B, C]
A Y [A, B]
Expected output: If the country is a neighbor, I'd like to add a column "Country Neighbor", which is a boolean value:
Country AnotherCountry AnotherCountryNeighbors CountryNeighbor
A X [B, C] False
A Y [A, B] True
Attempt: I tried using the dataframe.isin() function:
df.Country.isin(df.AnotherCountryNeighbors)
Error:
TypeError: unhashable type: 'list'
Upvotes: 1
Views: 211
Reputation: 164673
This is one occasion where I find list comprehension + zip
readable and efficient versus pandas
:
df['CountryNeighbor'] = [i in j for i, j in zip(df.Country, df.AnotherCountryNeighbors)]
Upvotes: 1
Reputation: 323226
Using in
with apply
df.apply(lambda x : x['Country'] in x['AnotherCountryNeighbors'],1)
Out[1425]:
0 False
1 True
dtype: bool
Your AnotherCountryNeighbors is list , isin
can not work with list values : iterable, Series, DataFrame or dictionary
Upvotes: 2