I’m trying to add more rows or records to my data frame, let’s say it looks like this:
JavaScript
x
4
1
ID age
2
44 23
3
31 25
4
and I have a CSV file stored in another data frame without headers
JavaScript
1
4
1
33 55
2
22 23
3
29 22
4
now I want a new data frame that looks like this
JavaScript
1
7
1
ID age
2
44 23
3
31 25
4
33 55
5
22 23
6
29 22
7
I have tried using append and concat but I didn’t get the result that I wanted
Advertisement
Answer
Assuming df1
/df2
, you can use set_axis
to copy the axis of the first DataFrame, then concat
:
JavaScript
1
2
1
out = pd.concat([df1, df2.set_axis(df1.columns, axis=1)], ignore_index=True)
2
output:
JavaScript
1
7
1
ID age
2
0 44 23
3
1 31 25
4
2 33 55
5
3 22 23
6
4 29 22
7
NB. ignore_index=True
is optional, this is just to avoid having duplicated indices. Without it:
JavaScript
1
7
1
ID age
2
0 44 23
3
1 31 25
4
0 33 55
5
1 22 23
6
2 29 22
7