python - 用 Pandas 中的 NaN 比较两列并得到差异

标签 python pandas numpy dataframe numpy-ndarray

我有以下数据框:

case c1   c2
1    x    x
2    NaN  y
3    x    NaN
4    y    x
5    NaN  NaN 
我想得到一列“匹配”,它将显示“c1”和“c2”中具有值的哪些记录相等或不同:
case c1   c2   match
1    x    x    True  
2    NaN  y    False
3    x    NaN  False
4    y    x    False
5    NaN  NaN  True 
我根据另一个堆栈溢出问题尝试了以下操作:Comparing two columns and keeping NaNs
但是,我无法同时正确处理第 4 种情况和第 5 种情况。
import pandas as pd
import numpy as np

df = pd.DataFrame({
    'case': [1, 2, 3, 4, 5],
    'c1': ['x', np.nan,'x','y', np.nan],
    'c2': ['x', 'y',np.nan,'x', np.nan],
})

cond1 = df['c1'] == df['c2']
cond2 = (df['c1'].isnull()) == (df['c2'].isnull())

df['c3'] = np.select([cond1, cond2], [True, True], False)

df

最佳答案

使用 eqisna :

df.c1.eq(df.c2)|df.iloc[:, 1:].isna().all(1)
#or
df.c1.eq(df.c2)|df.loc[:, ['c1','c2']].isna().all(1)

关于python - 用 Pandas 中的 NaN 比较两列并得到差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63459392/

相关文章:

python - 如何在 OpenShift 上配置 webpy 和 MySQL

python - 如何限制python pandas dataframes的操作区域?

python - 类型错误 : to_excel() got multiple values for argument 'sheet_name'

python - 在 matplotlib 中,为什么用细线绘图会更快?

python - NumPy 的/科学的 : fill upper triangle of array with elements of 1d vector?

python - 羽化裁剪边缘

python - 如何在 Python 中使用 smtplib 通过电子邮件发送 .html 文件

python - 确保 Python 计算器万无一失

python - Pandas |分组数据框中的 Fillna(ffill) 未填充

python - 格式化数据的快速查询