python - 检查两个列表是否在一个 pandas 列中

标签 python pandas

我有两个列表,其中包含字符串格式的术语。这些术语属于两类:水果和交通工具。我正在尝试显示仅包含来自冲突类别的成对术语的数据框。最好的方法是什么?下面是我的列表和数据框的示例。任何帮助将不胜感激!

  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/

相关文章:

python - 用平均值替换缺失值

python - 在对另一列进行分组后,查找列值的最大出现次数

python - 从 SQL 查询的 Python 列表中删除括号

python - Jupyter Notebook 无法打包 folium

python - Django 在 PermissionDenied 异常引发时打印错误

python - python2内部如何处理字符串和unicode?

python - 导入错误 : No module named 'pandas'

python - 如何使用panda.read_csv从python中的csv文件导入数据?

python - 使用 f.next() 迭代时倒带多行

python - 将 django 应用程序部署到 aws beanstalk 时的 requirements.txt 无效