Jerry
Jerry

Reputation: 77

How to concat several dataframes in one dataframe with pandas

I have several dataframes with 5 rows and 5 columns. How do I concat them so they will on under each other (I want to build csv file out of that). For example I have

df0

a/0/id a/0/team a/0/seed
6456   colorado  6
8978   oregon    7
0980   texas     1

df1

a/1/id a/1/team   a/1/seed
2342   nyc        12
8556   ucf        16
1324   california 5

How to get final dataframe like

final_df

6456   colorado   6
8978   oregon     7
0980   texas      1
2342   nyc        12
8556   ucf        16
1324   california 5

Thanks

Upvotes: 2

Views: 46

Answers (1)

jezrael
jezrael

Reputation: 862511

There is problem different columns names, so need some preprocessing before concat - e.g. split values by / and select last value - need same columns names for alignment in concat:

df0.columns = df0.columns.str.split('/').str[-1]
df1.columns = df1.columns.str.split('/').str[-1]
print (df0)
     id      team  seed
0  6456  colorado     6
1  8978    oregon     7
2   980     texas     1

print (df1)
     id        team  seed
0  2342         nyc    12
1  8556         ucf    16
2  1324  california     5

final_df = pd.concat([df0, df1], ignore_index=True)
print (final_df)
     id        team  seed
0  6456    colorado     6
1  8978      oregon     7
2   980       texas     1
3  2342         nyc    12
4  8556         ucf    16
5  1324  california     5

Upvotes: 1

Related Questions