![](/img/trans.png)
[英]Pandas dataframe - How to concatenate multiple dataframes having same column
[英]Pandas Python: Concatenate dataframes having same columns
我有 3 個具有相同列名的數據框。 說 :
df1
column1 column2 column3
a b c
d e f
df2
column1 column2 column3
g h i
j k l
df3
column1 column2 column3
m n o
p q r
每個數據框具有不同的值但具有相同的列。 我嘗試了 append 和 concat,以及合並外部,但有錯誤。 這是我嘗試過的:
df_final = df1.append(df2, sort=True,ignore_index=True).append2(df3, sort=True,ignore_index=True)
我也試過: df_final = pd.concat([df1, df2, df3], axis=1)
但是我收到這個錯誤: AssertionError: Number of manager items must equal union of block items# manager items: 61, # tot_items: 62
我已經用谷歌搜索了錯誤,但我似乎無法理解為什么會在我的情況下發生。 非常感謝任何指導!
我認為某些或所有 DataFrame 中存在重復的列名問題。
#simulate error
df1.columns = ['column3','column1','column1']
df2.columns = ['column5','column1','column1']
df3.columns = ['column2','column1','column1']
df_final = pd.concat([df1, df2, df3])
斷言錯誤:管理器項目的數量必須等於塊項目的並集#管理器項目:4,#tot_items:5
您可以找到重復的列名稱:
print (df3.columns[df3.columns.duplicated(keep=False)])
Index(['column1', 'column1'], dtype='object')
可能的解決方案是按列表設置列名:
df3.columns = ['column1','column2','column3']
print (df3)
column1 column2 column3
0 m n o
1 p q r
或者刪除重復名稱的重復列:
df31 = df3.loc[:, ~df3.columns.duplicated()]
print (df31)
column2 column1
0 m n
1 p q
然后concat
或append
應該工作得很好。
嘗試不提供軸示例:
import pandas as pd
mydict1 = {'column1' : ['a','d'],
'column2' : ['b','e'],
'column3' : ['c','f']}
mydict2 = {'column1' : ['g','j'],
'column2' : ['h','k'],
'column3' : ['i','i']}
mydict3= {"column1":['m','p'],
"column2":['n','q'],
"column3":['o','r']}
df1=pd.DataFrame(mydict1)
df2=pd.DataFrame(mydict2)
df3=pd.DataFrame(mydict3)
pd.concat([df1,df2,df3],ignore_index=True)
輸出
column1 column2 column3
0 a b c
1 d e f
0 g h i
1 j k i
0 m n o
1 p q r
給予
df1
column1 column2 column3
a b c
d e f
df2
column1 column2 column3
g h i
j k l
您可以在使用df.join()
方法時指定后綴。
df1.join(df2, lsuffix="_first", rsuffix=("_second"))
這將導致單個數據幀
df1
column1_first column2_first column3_first column1_second column2_second columnd 2_second
a b c g h i
d e f j k l
您可以在代碼中刪除axis=1
import pandas as pd
a = {"column1":['a','d'],
"column2":['b','e'],
"column3":['c','f']}
b = {"column1":['g','j'],
"column2":['h','k'],
"column3":['i','l']}
c = {"column1":['m','p'],
"column2":['n','q'],
"column3":['o','r']}
df1 = pd.DataFrame(a)
df2 = pd.DataFrame(b)
df3 = pd.DataFrame(c)
df_final = pd.concat([df1, df2, df3]) #.reset_index()
print(df_final)
#output
column1 column2 column3
0 a b c
1 d e f
0 g h i
1 j k l
0 m n o
1 p q r
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.