[英]Pandas: How to determine if a column value is in another column's list
Goal: I have this dataframe where I want to see if a "Country" belongs to "Another Country's Neighbors" list: 目标:我有这个数据框,我想看看“Country”是否属于“Another Country's Neighbors”列表:
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 Neighbor”列,这是一个布尔值:
Country AnotherCountry AnotherCountryNeighbors CountryNeighbor
A X [B, C] False
A Y [A, B] True
Attempt: I tried using the dataframe.isin() function: 尝试:我尝试使用dataframe.isin()函数:
df.Country.isin(df.AnotherCountryNeighbors)
Error: 错误:
TypeError: unhashable type: 'list'
Using in
with apply
使用
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 你AnotherCountryNeighbors是列表,
isin
不能与列表工作值:迭代,系列,数据帧或字典
这是我发现列表理解+ zip
可读和高效与pandas
一个场合:
df['CountryNeighbor'] = [i in j for i, j in zip(df.Country, df.AnotherCountryNeighbors)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.