I have a following dataframe:
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
我根据另一篇Stack Overflow的问题尝试了以下操作:比较两列并保留NaN值。然而,我无法正确处理第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
df.iloc[:, 1:].isna().all(1)
提供实际的列名? - verkter