[英]How to concat two or more data frames with different columns names in pandas
[英]Python Pandas - Concat two data frames with different number of rows and columns
我有兩個具有不同行號和列的數據幀。 兩個表都有幾個常見的列,包括“客戶ID”。 兩個表都看起來像這樣,大小分別為11697行×15列和385839行×6列。 客戶ID可能在第二個表中重復。 我想連接兩個表,並希望使用客戶ID合並類似的列。 我怎么能用python PANDAS做到這一點。 一張桌子看起來像這樣 -
我使用下面的代碼 -
pd.concat([df1, df2], sort=False)
只是想確保我沒有丟失任何信息? 如何檢查是否有多個帶有一個ID的條目,如何將其合並到一個結果中?
編輯 -
當我使用上面的代碼時,這里是數據集中NA'S的值之前和之后 -
有人能告訴我,哪里出錯了?
我相信DataFrame.merge
在這種情況下會起作用:
# use how='outer' to preserve all information from both DataFrames
df1.merge(df2, how='outer', on='customer_id')
如果兩個DataFrames的索引都設置為customer_id
那么DataFrame.join
也可以工作(它也更簡單):
df1 = df1.set_index('customer_id')
df2 = df2.set_index('customer_id')
df1.join(df2, how='outer')
pd.concat將在這里做的技巧,只需將axis設置為1以在第二軸(列)上連接,您應該首先為兩個數據幀設置索引到customer_id
import pandas as pd
pd.concat([df1.set_index('customer_id'), df2.set_index('customer_id')], axis = 1)
如果您想通過concatenaton省略具有空值的行,請使用dropna:
pd.concat([df1.set_index('customer_id'), df2.set_index('customer_id')], axis = 1).dropna()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.