Sort pandas dataframe by index then by alphabetical order

Viewed 404

I would like to sort a dataframe by index, and then by alphabetical order, in case some index values are identical.

df = pd.DataFrame()
df['values'] = ['d', 'c', 'b', 'a']
df['index'] = [2, 0, 1, 0]
df = df.set_index('index')

df.sort_index(inplace=True)

Which output

      values
index       
0          c
0          a
1          b
2          d

However, I am expecting:

      values
index       
0          a
0          c
1          b
2          d

Is there any way to achieve this consistently ? Thank you.

1 Answers

According to the official documentation, you can pass the index name into sort_values:

df.sort_values(['index','values'])

Output:

      values
index       
0          a
0          c
1          b
2          d

Fun: You can also sort by values, then sort again by index with a stable algorithm:

df.sort_values('values').sort_index(kind='mergesort')
Related