首页 > 解决方案 > 比较并查找 pandas 系列中缺失的字符串

问题描述

通过拥有以下两个熊猫系列,如何发现 df2 缺少'c'?或者索引 2 上存在缺失值。

df1 = pd.Series({'col1': ['a', 'b', 'c', 'd']})
df2 = pd.Series({'col2': ['a', 'b', 'd']})

可能会更容易的事情:我知道 df1 具有 df2 具有的所有值,并且我知道 df2 缺少多少值。

标签: pythonpandas

解决方案


您可以在系列中使用numpy.setdiff1d .values如下所示:

import pandas as pd
import numpy as np

df1 = pd.Series({'col1': ['a', 'b', 'c', 'd']})
df2 = pd.Series({'col2': ['a', 'b', 'd']})

print(np.setdiff1d(df1['col1'], df2['col2']))

输出:

['c']

推荐阅读