Pandas Python:连接具有相同列的数据帧

2024-04-28 14:54:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有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以及merge outer,但是有错误。 我试过的是:

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

我在谷歌上搜索了这个错误,但我似乎不明白为什么会发生在我的案例中。 任何指导都非常感谢!


Tags: 数据truedf错误itemssortfinaldf1
3条回答

我认为某些或所有数据帧中的列名重复存在问题。

#simulate error
df1.columns = ['column3','column1','column1']
df2.columns = ['column5','column1','column1']
df3.columns = ['column2','column1','column1']

df_final = pd.concat([df1, df2, df3])

AssertionError: Number of manager items must equal union of block items # manager items: 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

那么concatappend应该工作得很好。

您可以删除代码中的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

尝试不提供axis示例:

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

相关问题 更多 >