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
CodePudding user response:
I believe you want keys and names arguments:
result = pd.concat([df1, df2], keys=["df1", "df2"], names=["table", "junk"]).reset_index().drop(columns="junk")