I have to combine some dataframes in Python. I’ve tried to combine them using concat operation, but I am getting NaN values because each dataframe has different row size. For example:
JavaScript
x
16
16
1
DATAFRAME 1:
2
col1
3
0 1
4
DATAFRAME 2:
5
col2
6
0 5
7
DATAFRAME 3:
8
col3
9
0 7
10
1 8
11
2 9
12
COMBINED DATAFRAME:
13
col1 col2 col3
14
0 1.0 5.0 7
15
1 NaN NaN 8
16
2 NaN NaN 9
In this example, dataframe 1 and dataframe 2 only have 1 row. However, dataframe 3 has 3 rows. When I combine these 3 dataframes, I get NaN values for columns col1 and col2 in the new dataframe. I’d like to get a dataframe where the values for col1 and col2 are always the same. In this case, the expected dataframe would look like this:
JavaScript
1
5
1
EXPECTED DATAFRAME:
2
col1 col2 col3
3
0 1 5 7
4
1 1 5 8
5
2 1 5 9
Any idea? Thanks in advance
Advertisement
Answer
Use concat
and ffill
:
JavaScript
1
2
1
df = pd.concat([df1, df2, df3], axis=1).fill()
2