Reputation: 379
Hi all I have the following dataframe:
a LC_REF
5 Warranty Tsunami 1C17
6 10.1 1C17
7 5.2 1C17
...
5 Warranty Medium 1C17
6 9.1 1C17
7 6.3 1C17
...
5 Warranty Medium 2C17
6 4.2 2C17
7 3.1 2C17
...
5 Warranty High 2C17
6 2.1 2C17
7 0.5 2C17
I am trying to sort them by LC_REF, while maintaining the index order:
a LC_REF
5 Warranty Medium 2C17
6 4.2 2C17
7 3.1 2C17
...
5 Warranty High 2C17
6 2.1 2C17
7 0.5 2C17
...
5 Warranty Tsunami 1C17
6 10.1 1C17
7 5.2 1C17
...
5 Warranty Medium 1C17
6 9.1 1C17
7 6.3 1C17
However when I try:
df.sort_values('LC_REF')
I get a very out of order dataframe. Is there any way to sort by LC_REF while still maintaining the order that they are in?
Upvotes: 1
Views: 49
Reputation: 862661
It seems you need:
df.sort_values(['LC_REF'], ascending=False)
More general solution - first reset_index for original index values and second reset_index for original order and then sort by 2 columns:
df = df.reset_index()
.reset_index()
.sort_values(['LC_REF', 'level_0'], ascending=[False, True])
.set_index('index')
.drop('level_0', 1)
print (df)
a LC_REF
index
5 Warranty Medium 2C17
6 4.2 2C17
7 3.1 2C17
5 Warranty High 2C17
6 2.1 2C17
7 0.5 2C17
5 Warranty Tsunami 1C17
6 10.1 1C17
7 5.2 1C17
5 Warranty Medium 1C17
6 9.1 1C17
7 6.3 1C17
Upvotes: 1