有沒有辦法從第一個 DataFrame 中洗掉所有可以在第二個 DataFrame 中找到的行并添加僅在第二個 DataFrame 中獨占的行(= XOR)?這是一個轉折點:第一個 DataFrame 有一個列,在比較程序中應被忽略。
import pandas as pd
df1 = pd.DataFrame({'col1': [1,2,3],
'col2': [4,5,6],
'spec': ['A','B','C']})
df2 = pd.DataFrame({'col1': [1,9],
'col2': [4,9]})
result = pd.DataFrame({'col1': [2,3,9],
'col2': [5,6,9],
'spec': ['B','C','df2']})
df1 = df1.astype(str)
df2 = df1.astype(str)
這類似于 UNION(不是 UNION ALL)操作。
結合
col1 col2 spec
0 1 4 A
1 2 5 B
2 3 6 C
和
col1 col2
0 1 4
1 9 9
到
col1 col2 spec
1 2 5 B
2 3 6 C
1 9 9 df2
uj5u.com熱心網友回復:
您可以連接并洗掉重復項:
out = (pd.concat((df1, df2.assign(spec='df2')))
.drop_duplicates(subset=['col1','col2'], keep=False))
或過濾掉公共行并連接:
out = pd.concat((df1[~df1[['col1','col2']].isin(df2[['col1','col2']]).all(axis=1)],
df2[~df2.isin(df1[['col1','col2']]).all(axis=1)].assign(spec='df2')))
輸出:
col1 col2 spec
1 2 5 B
2 3 6 C
1 9 9 df2
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/439396.html
