Let's say you have two data frames:
import pandas as pd
df1 = pd.DataFrame(
{
"A": ["A0", "A1", "A3", "A5"],
"B": ["B0", "B1", "B3", "B5"],
},
index=[0, 1, 3, 5],
)
print(df1)
df2 = pd.DataFrame(
{
"A": ["A2", "A4"],
"B": ["B2", "B4"],
},
index=[2, 4],
)
print(df2)
How can I merge the two df1 and df2 frames in Python to obtain the following df3 data frame:
df3 = pd.DataFrame(
{
"A": ["A0", "A1", "A2", "A3", "A4", "A5"],
"B": ["B0", "B1", "B2", "B3", "B4", "B5"],
},
index=[0, 1, 2, 3, 4, 5],
)
print(df3)
The goal is to combine the two data frames into one.
Thanks
I tried the concat() function but it's not working as I want the indexes to be sorted in ascending order [0 1 2 3 4 5].
frames = [df1, df2]
df3 = pd.concat(frames)
CodePudding user response:
Adding sort_index
at the end
df3 = pd.concat(frames).sort_index()
df3
Out[85]:
A B
0 A0 B0
1 A1 B1
2 A2 B2
3 A3 B3
4 A4 B4
5 A5 B5