首頁  >  文章  >  後端開發  >  如何基於共享列組合 Pandas DataFrame:「join()」和「merge()」指南

如何基於共享列組合 Pandas DataFrame:「join()」和「merge()」指南

Barbara Streisand
Barbara Streisand原創
2024-10-24 22:10:02162瀏覽

How to Combine Pandas DataFrames Based on a Shared Column: A Guide to `join()` and `merge()`

在共享列上組合Pandas 資料框:綜合指南

簡介

組合多個資料框的資料是資料分析中的常見任務。 Pandas 提供了多種方法來實現這一點,包括 join() 和 merge() 函數。本文示範如何使用這些函數來組合共用公共列的兩個資料框。

使用 join() 函數

join() 函數預設執行內連接,這表示它只保留在連接列中具有匹配值的行。在提供的範例中,無法使用join() 函數,因為Restaurant_ids_dataframe 和Restaurant_review_frame 具有重疊的列名稱(星號和類型),如錯誤訊息所示:

Exception: columns overlap: Index([business_id, stars, type], dtype=object)

使用merge() 函數

merge() 函數為組合資料幀提供了更大的靈活性。若要執行外部連接(保留兩個資料幀中的所有行),請使用how='outer' 參數:

<code class="python">import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')</code>

預設情況下,merge() 使用後綴('_x', '_y ' ) 來區分具有重複名稱的列。要自訂後綴,請將值傳遞給suffixes 參數,如下所示:

<code class="python">pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer', suffixes=('_restaurant_id', '_restaurant_review'))</code>

結論

join() 和merge() 函數都可以用於組合資料框在公共列上。了解這些函數之間的差異對於實現所需的連接行為至關重要。 merge() 函數提供了更大的靈活性,包括執行外部聯結和自訂列後綴的能力。透過掌握這些技術,您可以有效地組合資料幀,從資料集中提取有意義的見解。

以上是如何基於共享列組合 Pandas DataFrame:「join()」和「merge()」指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn