对 Pandas 数据框进行排序并打印最高的 n 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16958499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:10:03  来源:igfitidea点击:

Sort Pandas dataframe and print highest n values

pandassortingdataframemax

提问by Nilani Algiriyage

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?

我有一个熊猫数据框,我想按降序对列('字节')进行排序,并打印最高的 10 个值及其相关的“客户端 IP”列值。假设以下是我的数据帧的一部分。我有很多不同的方法都失败了?

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()

回答by jezrael

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

我认为你可以使用nlargest(新pandas版本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

回答by Andy Hayden

Note:sortis deprecated - use sort_valuesinstead

注意:sort已弃用 -sort_values改用

To sortdescending use ascending=False:

sort降的使用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).

要获取前 10 个值,请使用.head(10).

回答by Nilani Algiriyage

df['Bytes'] = df['Bytes'].astype('int')
print df.sort('Bytes', ascending=False).head(10)[['Bytes', 'Client-IP']]

I could solve it using above code with the help of Andy Hayden. :D

我可以在 Andy Hayden 的帮助下使用上面的代码解决它。:D

回答by megamind

df[['Bytes', 'Client Ip']].sort_values('Bytes', ascending=False).nlargest(10, 'Bytes')

This should get you everything you need 1) Sorting Bytes 2) Returning the Largest 10 Bytes values

这应该为您提供所需的一切 1) 字节排序 2) 返回最大的 10 字节值