Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort one column without changing other columns in pandas?

Example: Current df looks like:

    df=
    A B
    1 5
    2 6
    3 8
    4 1

I want the resulting df to be like this (B is sorted and A remains untouched):

    df=
    A B
    1 8
    2 6
    3 5
    4 1
like image 909
D. Rao Avatar asked Nov 16 '25 17:11

D. Rao


2 Answers

You need to break an internal Pandas security mechanism - aligning by index, which takes care of the data consistency. So assigning 1D Numpy array or a vanilla Python list would do the trick, because both of them don't have an index, so Pandas can't do alignment:

df['B'] = df['B'].sort_values(ascending=False).values

or

df['B'] = df['B'].sort_values(ascending=False).tolist()

both yield:

In [77]: df
Out[77]:
   A  B
0  1  8
1  2  6
2  3  5
3  4  1
like image 91
MaxU - stop WAR against UA Avatar answered Nov 18 '25 07:11

MaxU - stop WAR against UA


You can do this as well :

df['B'] = sorted(df['B'].tolist())[::-1]
like image 29
Sankar Avatar answered Nov 18 '25 07:11

Sankar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!