合并熊猫数据框[反联接]

时间:2020-02-09 19:25:16

标签: python pandas join merge anti-join

我有两个数据集:

  • a.csv
id,name,gender,age,smoke
1,John,M,16,Y
2,Mary,F,15,Y
  • b.csv
id,name,gender,age,smoke
1,John,M,16,Y
2,Mary,F,15,N

我想要: 年龄和烟雾匹配但性别不匹配的Recods。

我的尝试: 做这项工作,但不确定是否正确。

df1 = pd.read_csv('data/a.csv')
df2 = pd.read_csv('data/b.csv')
df1.set_index(['age', 'smoke'], inplace=True)
df2.set_index(['age', 'smoke'], inplace=True)
result = df1.join(df2, how='inner', lsuffix='_a', rsuffix='_b')
print(result[result['gender_a'].astype(str) != result['gender_b'].astype(str)])

0 个答案:

没有答案