[SOLVED] how to combine two dataframe in python

Issue

This Content is from Stack Overflow. Question asked by Codak

I have the following code, while combining, I want a new column at the beginning and write each table name (df1 and df2)

import pandas as pd
# First DataFrame
df1 = pd.DataFrame({'id': ['A01', 'A02', 'A03', 'A04'],
                    'Name': ['ABC', 'PQR', 'DEF', 'GHI']})
  
# Second DataFrame
df2 = pd.DataFrame({'id': ['B05', 'B06', 'B07', 'B08'],
                    'Name': ['XYZ', 'TUV', 'MNO', 'JKL']})
  
  
frames = [df1, df2]
  
result = pd.concat(frames)
display(result)


    id  Name
0   A01 ABC
1   A02 PQR
2   A03 DEF
3   A04 GHI
0   B05 XYZ
1   B06 TUV
2   B07 MNO
3   B08 JKL



Solution

I believe you want keys and names arguments:

result = pd.concat([df1, df2], keys=["df1", "df2"], names=["table", "junk"]).reset_index().drop(columns="junk")


This Question was asked in StackOverflow by Codak and Answered by Jason Baker It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?