我有两个列表,其中包含字符串格式的术语。这些术语属于两类:水果和交通工具。我正在尝试显示仅包含来自冲突类别的成对术语的数据框。最好的方法是什么?下面是我的列表和数据框的示例。任何帮助将不胜感激!
dataframe:
col 1
['apple', 'truck' ]
['truck', 'orange']
['pear', 'motorcycle']
['pear', 'orange' ]
['apple', 'pear' ]
['truck', 'car' ]
vehicles = ['car', 'truck', 'motorcycle']
fruits = ['apple', 'orange', 'pear']
desired output:
col 2
['apple', 'truck' ]
['pear', 'motorcycle']
['truck', 'orange']
最佳答案
从列表列创建 DataFrame
,通过 DataFrame.isin
测试成员资格, 然后通过 ~
反转掩码,用 DataFrame.any
检查每行至少一个 True
对于列表和最后一个链条条件,按位 AND - &
过滤 boolean indexing
:
df1 = pd.DataFrame(df['col 1'].values.tolist())
df = df[(~df1.isin(vehicles)).any(axis=1) & (~df1.isin(fruits)).any(axis=1)]
print (df)
col 1
0 [apple, truck]
1 [truck, orange]
2 [pear, motorcycle]
另一种解决方案是 set
的交集由 和
链接(因为是标量)并转换为 bool
- 空集被转换为 错误
:
def func(x):
s = set(x)
v = set(vehicles)
f = set(fruits)
return bool((s & v) and (s & f))
df = df[df['col 1'].apply(func)]
print (df)
col 1
0 [apple, truck]
1 [truck, orange]
2 [pear, motorcycle]
关于python - 检查两个列表是否在一个 pandas 列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55181914/