簡體   English   中英

無論行中的順序如何,都將Pandas DataFrames合並為兩列值

[英]Merge Pandas DataFrames on Two Column Values Irrespective of Order in Row

給出兩個數據幀:

df1 = pd.DataFrame([
                   ['Red', 'Blu', 1.1],
                   ['Yel', 'Blu', 2.1],
                   ['Grn', 'Grn', 3.1]], columns=['col_1a','col_1b','score_1'])

df2 = pd.DataFrame([
                   ['Blu', 'Red', 1.2],
                   ['Yel', 'Blu', 2.2],
                   ['Vio', 'Vio', 3.2]], columns=['col_2a','col_2b','score_2'])

我想將它們合並在兩個列上,如下所示:

df3 = pd.DataFrame([
                   ['Blu', 'Red', 1.1, 1.2],
                   ['Yel', 'Blu', 2.1, 2.2],
                   ], columns=['col_a','col_b','score_1','score_2'])

警告1:列內容的順序可以在數據幀之間切換以進行合並。 例如,第一行應該合並,因為它包含“紅色”和“藍色”,即使它們出現在不同的列中。

警告2:最終df_3中列的順序並不重要。 “Blu”是否在col_acol_b中並不意味着什么。

警告3:忽略任何其他不匹配的東西,如最后一行

您可以對行中的前兩列進行排序,然后合並它們:

# rename column names
cols = ['col_a', 'col_b']
df1.columns = cols + ['score_1']
df2.columns = cols + ['score_2']

# sort the two id columns along the row
df1[cols] = pd.np.sort(df1[cols], axis=1)
df2[cols] = pd.np.sort(df2[cols], axis=1)

# merge
df1.merge(df2)

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM