Stack row under row from two different dataframe using python?

Viewed 22
index col 1 col 2
First row 1 row 2
Second row 3 row 4
index col 3 col 4
First row 5 row 6
Second row 7 row 8
index 1 2
First row 1 row 2
row 5 row 6
Second row 3 row 4
row 7 row 8
1 Answers

here is one way to do it, concat that two DF.

#the columns needs to be same in order to align, so generate new col names 
df.columns=['col' + str(idx) if col[:3] =='col' else col for idx, col in enumerate(df.columns)]

df2.columns=['col' + str(idx) if col[:3] =='col' else col for idx, col in enumerate(df2.columns)]

#concat
pd.concat([df, df2], ignore_index=True).sort_values('index')

index   col1    col2
0   First   row 1   row 2
2   First   row 5   row 6
1   Second  row 3   row 4
3   Second  row 7   row 8
Related