简体   繁体   中英

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 ie 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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM