[英]Python, Pandas: Compare two dataframes and return combined
晚上好,
我想知道,比較兩個數據幀並返回它們的組合的最佳方法是什么? 或者,如果 pandas 內部甚至有內置 function?
例如,這是我的兩個數據框:
Dataframe 01:
first_name | age | id | value_a | value_b | value_c
peter | 37 | 19 | 4562 | 78 | 21.5
jane | 32 | 5 | 3832 | 85 | 17.0
michael | 43 | 41 | 2195 | 63 | 44.4
Dataframe 02:
first_name | age | id | value_a | value_b | value_c
sarah | 51 | 2 | 63 | 81 | 4.1
peter | 37 | 19 | 4562 | 81 | 21.5
tom | 22 | 89 | 107 | 14 | 0.0
michael | 43 | 41 | 1838 | 63 | 44.4
如您所見,整個 dataframe(Dataframe 02)中有一些新條目,並且還列出了一些已經存在的條目 --> 在這些行中進行了一些更改? 我想要實現的是一個 new(,) dataframe 包含所有新行:已經存在的行和更新的行! 在這種情況下:
Dataframe 新
first_name | age | id | value_a | value_b | value_c
peter | 37 | 19 | 4562 | 81 | 21.5
jane | 32 | 5 | 3832 | 85 | 17.0
michael | 43 | 41 | 1838 | 63 | 44.4
sarah | 51 | 2 | 63 | 81 | 4.1
tom | 22 | 89 | 107 | 14 | 0.0
筆記:
感謝您的所有幫助和美好的夜晚!
既然您問pandas 內部是否還有內置的 function? . 答案是肯定的,在 pandas 中有一個內置的 function 允許您比較相同標記(具有相同索引和列)的數據幀。
There is a DataFrame.compare
function which is available in pandas version >= 1.1.0
and allows you to compare first dataframe to second DataFrame and show the differences:
所以,現在讓我們看看你所說的例子
- 總有一個列(這里:'id')可以看作是一個不變的鍵
- 列的數量和名稱始終保持不變
因此,為了比較兩個數據幀,您首先需要align
index
這可以使用DataFrame.align
id
來完成
d1, d2 = df1.set_index('id').align(df2.set_index('id'))
現在您可以在對齊的數據幀上使用DataFrame.compare
:
d1.compare(d2, keep_equal=True)
結果:
first_name age value_a value_b value_c
self other self other self other self other self other
id
2 NaN sarah NaN 51.0 NaN 63.0 NaN 81.0 NaN 4.1
5 jane NaN 32.0 NaN 3832.0 NaN 85.0 NaN 17.0 NaN
19 peter peter 37.0 37.0 4562.0 4562.0 78.0 81.0 21.5 21.5
41 michael michael 43.0 43.0 2195.0 1838.0 63.0 63.0 44.4 44.4
89 NaN tom NaN 22.0 NaN 107.0 NaN 14.0 NaN 0.0
現在來回答你的第二個問題:
如何實現一個新的(?)dataframe,其中包含所有新行,已經存在的行和更新的行!
您可以在對齊的數據幀d1
和d2
上使用DataFrame.comine_first
:
d2.combine_first(d1)
或者,在未對齊的情況下,如下所示:
df2.set_index('id').combine_first(df1.set_index('id'))
結果:
first_name age value_a value_b value_c
id
2 sarah 51.0 63.0 81.0 4.1
5 jane 32.0 3832.0 85.0 17.0
19 peter 37.0 4562.0 81.0 21.5
41 michael 43.0 1838.0 63.0 44.4
89 tom 22.0 107.0 14.0 0.0
這是一種方法
>>> (pd.concat([df1, df2])
.drop_duplicates(subset=['id','first_name'], keep='last')
.reset_index(drop=True)
.set_index('first_name')
)
first_name | age | id | value_a | value_b | value_c
jane | 32 | 5 | 3832 | 85 | 17.0
sarah | 51 | 2 | 63 | 81 | 4.1
peter | 37 | 19 | 4562 | 81 | 21.5
tom | 22 | 89 | 107 | 14 | 0.0
michael | 43 | 41 | 1838 | 63 | 44.4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.