Home > Net >  How to concatenate dataframes considering column orders
How to concatenate dataframes considering column orders

Time:12-05

I want to combine two dataframes:

df1=pd.DataFrame({'A':['a','a',],'B':['b','b']})
df2=pd.DataFrame({'B':['b','b'],'A':['a','a']})
pd.concat([df1,df2],ignore_index=True)

result:

enter image description here

But I want the output to be like this (I want the same code as SQL's union/union all):

enter image description here

CodePudding user response:

Another way is to use numpy to stack the two dataframes and then use pd.DataFrame constructor:

pd.DataFrame(np.vstack([df1.values,df2.values]), columns = df1.columns)

Output:

   A  B
0  a  b
1  a  b
2  b  a
3  b  a

CodePudding user response:

Here is a proposition to do an SQL UNION ALL with pandas by using pandas.concat :

list_dfs = [df1, df2]

out = (
        pd.concat([pd.DataFrame(sub_df.to_numpy()) for sub_df in list_dfs], 
                  ignore_index=True)
            .set_axis(df1.columns, axis=1)
      )

# Output :

print(out)

   A  B
0  a  b
1  a  b
2  b  a
3  b  a
  • Related