Home > database >  Concatinating the dataframe in pandas so that the indexes are placed one after the other
Concatinating the dataframe in pandas so that the indexes are placed one after the other

Time:01-11

I have two dataframes created using pandas, I want to concatenate them so that the indexes of the two come one after the other. For example,

df1:

    x    y
a   10   30
b   20   40

df2:

    x    y
a1  11   31
b1  21   41

required output:

    x    y
a   10   30
a1  11   31
b   20   40
b1  21   41

CodePudding user response:

You need to concatenate the two dataframes and then sort the indeces:

pd.concat([df1, df2]).sort_index()

Output:

     x   y
a   10  30
a1  11  31
b   20  40
b1  21  41

CodePudding user response:

You can assign a counter ("order"), concat, and use a stable sorting to reorder in an alternating way with the sort='stable' parameter of sort_values:

out = (pd
   .concat([df1.assign(order=range(len(df1))),
            df2.assign(order=range(len(df2)))])
   .sort_values(by='order', kind='stable')
   .drop(columns='order')
)

NB. this works independently of the length of the two dataframes and the original order of the indices.

Output:

     x   y
a   10  30
a1  11  31
b   20  40
b1  21  41

Intermediate after concat:

     x   y  order
a   10  30      0
b   20  40      1
a1  11  31      0
b1  21  41      1
  • Related