hyeri
hyeri

Reputation: 693

Sort index order with duplicate index numbers

I have two dataframes

df1:

         Type         Number
24       variation     2.5
25       variation     2.6
26       variation      4
27       variation      4

dfn:

          Type         Number
24       variable
26       variable

I'm trying to append these two data frames and sort them by index

dfn = dfn.append(df).sort_index()

The end result should be

          Type         Number
24       variable
24       variation     2.5
25       variation     2.6
26       variable
26       variation      4
27       variation      4

However, I am getting results like:

          Type         Number
24       variable
24       variation     2.5
25       variation     2.6
26       variation      4
26       variable
27       variation      4

I want the row with variable type above the variation type, which works fine with the first index (24) but not for the next index (26) and so on. How can I get the desired results?

Upvotes: 1

Views: 794

Answers (2)

wwnde
wwnde

Reputation: 26676

Please Try, append, reset index, sort values by multiple columns and drop the reset index column as follows

df1.append(dfn).reset_index().sort_values(['index','Type','Number']).drop('index',1)

Upvotes: 1

BENY
BENY

Reputation: 323226

Let us try

dfn = df.append(dfn).sort_index()

Upvotes: 1

Related Questions