簡體   English   中英

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

[英]Pandas: How to determine if a column value is in another column's list

目標:我有這個數據框,我想看看“Country”是否屬於“Another Country's Neighbors”列表:

Country     AnotherCountry  AnotherCountryNeighbors
A           X                [B, C]
A           Y                [A, B]

預期輸出:如果國家是鄰居,我想添加一個“Country Neighbor”列,這是一個布爾值:

Country     AnotherCountry  AnotherCountryNeighbors   CountryNeighbor
A           X                [B, C]                    False
A           Y                [A, B]                    True

嘗試:我嘗試使用dataframe.isin()函數:

df.Country.isin(df.AnotherCountryNeighbors)

錯誤:

TypeError: unhashable type: 'list'

使用in with apply

df.apply(lambda x :  x['Country'] in x['AnotherCountryNeighbors'],1)
Out[1425]: 
0    False
1     True
dtype: bool

你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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM