0

Assume I have a Pandas Dataframe as such:

Col_A   Col_B   Col_C
  501     A       2
  501     G       19
  501     B       10
  501     Z       32
  502     B        7
  502     J       34
  502     M        8
  502     S       90

I am looking for a way to apply multiple sorts to one dataframe. For example, Where Col_A = 501, Col_B & Col_C would be ascending. And where Col_A = 502, Col_B & Col_C would be descending as such:

Col_A   Col_B   Col_C
 501     A       2
 501     B       10
 501     G       19
 501     Z       32
 502     S       90
 502     M       34
 502     J       8
 502     B       7

Any help would be much appreciated!

dmd7
  • 605
  • 3
  • 8
  • Try this : https://stackoverflow.com/questions/34347041/pandas-sort-a-column-by-values-in-another-column][1] – K.J Fogang Fokoa May 06 '20 at 21:52
  • Does this answer your question? [How to sort a dataFrame in python pandas by two or more columns?](https://stackoverflow.com/questions/17141558/how-to-sort-a-dataframe-in-python-pandas-by-two-or-more-columns) – AMC May 06 '20 at 22:22

1 Answers1

0

Something like this would work:

In [2132]: d1 = df[df['Col_A'].eq(501)].sort_values(by=['Col_B', 'Col_C'])

In [2133]: d2 = df[df['Col_A']eq(502)].sort_values(by=['Col_B', 'Col_C'], ascending=False)

In [2137]: df = d1.append(d2)

In [2138]: df
Out[2138]: 
   Col_A Col_B  Col_C
0    501     A      2
2    501     B     10
1    501     G     19
3    501     Z     32
7    502     S     90
6    502     M      8
5    502     J     34
4    502     B      7
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58