1

I have a big DataFrame with 10 columns. I want to sort all rows just for specific columns (two). For example, if this be my data frame

      A  B  C
   0  5  1  8
   1  8  2  2
   2  9  3  3

I want it to sort it just for A and B but for rows so the answer should be like :

  A  B  C
0 1  5  8
1 2  8  2
2 3  9  3

Thank you.

2 Answers 2

2

Call np.sort on that specific subslice of columns and assign it back using loc:

# df.loc[:, ['A', 'B']] = np.sort(df.loc[:, ['A', 'B']], axis=1)   
df.loc[:, ['A', 'B']] = np.sort(df.loc[:, ['A', 'B']])                                                                 
df                                                                                                                     

   A  B  C
0  1  5  8
1  2  8  2
2  3  9  3
Sign up to request clarification or add additional context in comments.

Comments

1

I am using sort

s=df[['A','B']]
s.values.sort()
df.update(s)
df
   A  B  C
0  1  5  8
1  2  8  2
2  3  9  3

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.