programmer_04_03
programmer_04_03

Reputation: 181

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

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

Upvotes: 2

Views: 43

Answers (2)

mozway
mozway

Reputation: 260745

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

Upvotes: 1

ali bakhtiari
ali bakhtiari

Reputation: 1097

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

Upvotes: 2

Related Questions