user517696
user517696

Reputation: 2672

How do i sort the values in a dataframe in pandas?

I have a dataframe like this:

 innings    batsman     batsman_runs
    1          AA Noffke     9
    1          B Akhil       0
    1          BB McCullum  158
    1          CL White      6
    1          DJ Hussey     12....

I need to sort the batsman_runs in descending order and also show their corresponding batsman i.e if 158 is at the top, then BB McCullum should be in the adjacent cell. I tried the following code:

df['batsman_runs'].sort_values(ascending=False)

But this code does not show the batsman name. How do i show the runs with the corresponding batsman ?

Upvotes: 0

Views: 76

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

try this:

In [32]: df.sort_values('batsman_runs', ascending=0)
Out[32]:
   innings      batsman  batsman_runs
2        1  BB McCullum           158
4        1    DJ Hussey            12
0        1    AA Noffke             9
3        1     CL White             6
1        1      B Akhil             0

or:

In [31]: df.sort_values('batsman', ascending=0)
Out[31]:
   innings      batsman  batsman_runs
4        1    DJ Hussey            12
3        1     CL White             6
2        1  BB McCullum           158
1        1      B Akhil             0
0        1    AA Noffke             9

you can also combine several columns:

In [34]: df.sort_values(['batsman','batsman_runs'], ascending=[1,0])
Out[34]:
   innings      batsman  batsman_runs
0        1    AA Noffke             9
1        1      B Akhil             0
2        1  BB McCullum           158
3        1     CL White             6
4        1    DJ Hussey            12

Upvotes: 5

Related Questions