我有兩個具有相同列標題的資料集,我想洗掉所有 100% 相同的資料,只保留它們沒有完全相同的內容。我怎么能這樣做呢?

感謝您的時間!
uj5u.com熱心網友回復:
要獲得除了兩個 pandas 資料集的交集之外的所有內容,請嘗試以下操作:
# Everything from the first except what is on second
r1 = df1[~df1.isin(df2)]
# Everything from the second except what is on first
r2 = df2[~df2.isin(df1)]
# concatenate and drop NANs
result = pd.concat(
[r1, r2]
).dropna().reset_index(drop=True)
但是有一個警告,當使用布爾掩碼過濾時,您的 int 值可能會變成浮點數。默認情況下,pandas 用浮點版本的 NAN 替換不需要的 (False) 值,并將整個列轉換為浮點數。您可以在下面的示例中看到這種情況。
為了避免這種情況,請在創建資料框時顯式宣告資料型別。
例子
import pandas as pd
df1 = pd.read_csv("./csv1.csv") #, dtype='Int64')
print(f"csv1\n{df1}\n")
df2 = pd.read_csv("./csv2.csv") #, dtype='Int64')
print(f"csv2\n{df2}\n")
# Everything from first except what is on second
r1 = df1[~df1.isin(df2)]
# Everything from second except what is on first
r2 = df2[~df2.isin(df1)]
# concatenate and drop NANs
result = pd.concat(
[r1, r2]
).dropna().reset_index(drop=True)
print(f"result\n{result}\n")
輸入
csv1
A B C
0 1 2 3
1 4 5 6
2 7 8 9
csv2
A B C
0 1 2 3
1 4 5 6
2 10 11 12
輸出
result
A B C
0 7.0 8.0 9.0
1 10.0 11.0 12.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/422824.html
標籤:
下一篇:連接具有相同列的表
