簡體   English   中英

如何在 Python Pandas 中合並兩個數據幀,其中關鍵列名稱不同,但想要從第二個數據幀中檢索某些列?

[英]How to merge two dataframes in Python Pandas, where key column names different, but want to retrieve SOME of the columns from second dataframe?

我試圖將一個數據幀中的幾列合並到另一個數據幀中,但兩個數據幀上的關鍵列未正確命名。 如果您查看圖片“原始兩個數據幀”,Table_1 具有關鍵列“CostCenter”,而 Table_2 具有關鍵列“CC”。 我希望最終結果看起來像標題為“新數據框”的圖片。 正如您所看到的,我只是從 Table_2 中檢索“Fixed/Variable”和“CostCenterName”,而不是從“CC”、“CostCenterSummary”和“Organization”列中取出。

感謝您的幫助! - 吉姆

原來的兩個數據框新的數據框

首先,您可以重命名 table1 的鍵:

table1.rename(columns={"CostCenter":"CC","CostCenterSummary":"Organization"},inplace = True)

然后合並表:

result = pd.merge(table1, table2, on=['CC','Organization'])

並返回您的鑰匙:

table1.rename(columns={"CC":"CostCenter","Organization":"CostCenterSummary"},inplace = True)

完成此操作的一行解決方案:(屏幕截圖中的 df1 是 Table1,df2 是 Table2)

df = pd.merge(df1, df2, left_on="CostCenter", right_on="CC")[['CostCenter','CostCenterSummary','Fixed/Variable','CostCenterName']]

印刷:

   CostCenter CostCenterSummary Fixed/Variable            CostCenterName
0        8308           Finance       Variable       AccountingCorporate
1        8354           Finance       Variable  Accounting International
2        8372           Finance          Fixed        AccountingDomestic

暫無
暫無

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

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