Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Pandas dataframe and print highest n values

I have a pandas data frame and I want to sort column('Bytes') in Descending order and print highest 10 values and its related "Client IP" column value. Suppose following is a part of my dataframe. I have many different methods and failed?

0       Bytes    Client Ip                 0       1000      192.168.10.2     1       2000      192.168.10.12     2       500       192.168.10.4      3       159       192.168.10.56  

Following prints only the raw which has the highest value.

print df['Bytes'].argmax() 
like image 705
Nilani Algiriyage Avatar asked Jun 06 '13 09:06

Nilani Algiriyage


People also ask

How do you sort a DataFrame by the highest value?

To sort a dataframe based on the values of a column but in descending order so that the largest values of the column are at the top, we can use the argument ascending=False.

How do Pandas sort data from highest to lowest?

In order to sort the data frame in pandas, function sort_values() is used. Pandas sort_values() can sort the data frame in Ascending or Descending order.


2 Answers

I think you can use nlargest (New in pandas version 0.17.0):

print df    0  Bytes  Client             Ip 0  1      1    1000   192.168.10.2 1  0      0    2000  192.168.10.12 2  2      2     500   192.168.10.4 3  3      3     159  192.168.10.56  print df.nlargest(3, 'Client')    0  Bytes  Client             Ip 1  0      0    2000  192.168.10.12 0  1      1    1000   192.168.10.2 2  2      2     500   192.168.10.4 
like image 85
jezrael Avatar answered Oct 01 '22 12:10

jezrael


Note: sort is deprecated - use sort_values instead

To sort descending use ascending=False:

In [6]: df.sort('Bytes', ascending=False) Out[6]:    0  Bytes      Client Ip 1  1   2000  192.168.10.12 0  0   1000   192.168.10.2 2  2    500   192.168.10.4 3  3    159  192.168.10.56 

To take the first 10 values use .head(10).

like image 21
Andy Hayden Avatar answered Oct 01 '22 11:10

Andy Hayden