-1

I'm trying to sort two pandas dataframe columns. I understand that Python has its own built-in function:

.sort()

But I'm wondering if Pandas has this function too and if it can be done with two columns together, as a pair.

Say for example I have the following dataset:

   sum         feature        
0  5.1269        3
1  2.8481        2     
2  -1.472        1  
3  -3.212        0

I want to obtain this:

   sum         feature        
0  -3.212        0
1  -1.472        1     
2  2.8481        2  
3  5.1269        3

Basically what I am doing here, is I am sorting the column 'feature' to get it from minimum to maximum, however I want the corresponding values in 'sum' to also change.

Can someone please help me out with this? I have seen other posts around Stackoverflow on this, however I have not found a detailed answer explaining the process, or an answer for this specific question.

0

1 Answer 1

2

Just use:

df.sort_values('feature')

For resetting index:

df=df.sort_values('feature').reset_index(drop=True)
print(df)

      sum  feature
0 -3.2120        0
1 -1.4720        1
2  2.8481        2
3  5.1269        3
Sign up to request clarification or add additional context in comments.

5 Comments

Does this also sort the values in 'sum'?
@Saurish yes it does
@Saurish If your features are unique, this is the best solution. although if you have repeating feature values with different sums, then you may use: df.sort_values(['feature', 'sum']), in that order
I Agree with @MohitMotwani :)
Thanks guys; as @jezrael already pointed out that this question is a duplicate; I guess I'm awful at searching through Stackoverflow. The information helped me out a ton. Thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.