简体   繁体   English

Pandas:如何确定列值是否在另一列的列表中

[英]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.

相关问题 查找 pandas 列中的值是否在另一列的列表中 - find if the value in pandas column is in another column's list 检查 pandas 列值是否在另一列的列表中 - Check if pandas column value is inside another column's list 如何确定熊猫列中值的“稳定性”? - how can I determine a value's 'stability' in a pandas' column? 对于Pandas数据框中的每一行,确定另一列中是否存在一列值 - For every row in Pandas dataframe determine if a column value exists in another column 确定熊猫数据框中每列的最大值 - determine column maximum value per another column in pandas dataframe 如何在另一列中搜索当前列的值,然后在pandas中与其相邻的另一列中显示它的id? - How to search the value of current column in another column then display it's id in another column adjacent to it in pandas? 如何根据 pandas 中另一列的值组合字符串列表的行? - How to combine rows of list of string based on another column's value in pandas? python pandas:检查数据帧的列值是否在另一个数据帧的列中,然后计数并列出它 - python pandas: Check if dataframe's column value is in another dataframe's column, then count and list it 如何将一列除以另一列,其中一个数据帧的列值对应于 Python Pandas 中另一个数据帧的列值? - How to divide one column by another where one dataframe's column value corresponds to another dataframe's column's value in Python Pandas? 检查熊猫列值是否存在于另一个熊猫列(列表)中 - Checking if a pandas column value is present in another pandas column (list)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM