D. Rao
D. Rao

Reputation: 523

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

Upvotes: 4

Views: 6523

Answers (2)

Sankar
Sankar

Reputation: 586

You can do this as well :

df['B'] = sorted(df['B'].tolist())[::-1]

Upvotes: 1

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210882

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

Upvotes: 14

Related Questions