首頁  >  文章  >  後端開發  >  如何解決將 Pandas 資料框與「join()」組合時出現的欄位重疊錯誤?

如何解決將 Pandas 資料框與「join()」組合時出現的欄位重疊錯誤?

Patricia Arquette
Patricia Arquette原創
2024-10-27 06:07:03206瀏覽

How to Resolve Column Overlap Errors While Combining Pandas Data Frames with `join()`?

使用公共列上的Merge 組合Pandas 資料框

在處理資料分析任務時,通常需要將來自多個來源的資料組合到單一資料框中。 Pandas 提供了多種執行資料框連接的方法,其中之一是 merge(),它使我們能夠基於公共列組合資料框。

假設我們有兩個資料框:

restaurant_ids_dataframe:

Column Name Data Type
business_id int
categories object
city object
full_address object
latitude float
longitude float
name object
neighborhoods object
open bool
review_count int
stars float
state object
type object

restaurant_view >目標是使用DataFrame.join 將這些資料幀組合成單一資料幀() 方法。我們通常期望在公共列business_id 上執行聯結。但是,當嘗試以下程式碼行時:

Column Name Data Type
business_id int
date object
review_id int
stars float
text object
type object
user_id int
votes int

我們收到錯誤:

restaurant_review_frame.join(other=restaurant_ids_dataframe, on='business_id', how='left')

要解決此問題,我們應該使用merge() 方法,並指定on 參數中的公共列。 merge() 方法旨在處理重疊列並相應地組合資料幀。語法為:

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

這裡,how 參數定義要執行的連線類型。在本例中,我們使用了 external,它執行完整的外連接,組合兩個資料幀中的所有行。

<code class="python">import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')</code>
此外,我們可以使用 suffixes 參數指定合併列的後綴,從而允許我們自訂結果資料框中的列名稱。例如,要將列後綴為star_restaurant_id 和star_restaurant_review,我們可以使用:

merge() 方法提供了一組全面的參數,可以對連接操作提供細粒度的控制,從而實現高效且準確的數據框組合。

以上是如何解決將 Pandas 資料框與「join()」組合時出現的欄位重疊錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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