数据框中的n个最大值

时间:2019-04-19 18:56:58

标签: python pandas max

我有一个熊猫数据框,例如:

upstream docker {
    server localhost:8701;
    server localhost:8702;
  }

server {
    server_name my_website;
    location / {
      proxy_pass http://docker;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
      # proxy_set_header                HTTP_Country-Code $geoip_country_code;
        proxy_pass_request_headers      on;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my_website/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my_website/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

server {
    if ($host = my_website) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    server_name my_website;
    return 404; # managed by Certbot

}

我想得到类似9个(行数)最高值的索引,或者类似每列最高值的计数之类的东西:

        column0     column1     column2     column3     column4
row0    179319.0    180895.0    94962.0     130734.0    0
row1    89659.5     90447.5     47481.0     65367.0     0
row2    59773.0     60298.33333 31654.0     43578.0     0
row3    44829.75    45223.75    23740.5     32683.5     0
row4    35863.8     36179.0     18992.4     26146.8     0
row5    29886.5     30149.16666 15827.0     21789.0     0
row6    25617.0     25842.14285 13566.0     18676.28571 0
row7    22414.875   22611.875   11870.25    16341.75    0
row8    19924.33333 20099.44444 10551.33333 14526.0     0

在我的示例中,最高的9个值分别是row0的column0,column1,column2和column3的值,row1的column0,column1和column3的数据,以及row2的column0和column1的数据。 >

有什么想法吗?谢谢!

4 个答案:

答案 0 :(得分:7)

IIUC nlargeststack之后

df.stack().nlargest(9).groupby(level=1).count().reindex(df.columns,fill_value=0)
Out[48]: 
column0    3
column1    3
column2    1
column3    2
column4    0
dtype: int64

答案 1 :(得分:3)

IIUC,您可以堆叠和排序

df.stack().sort_values(ascending = False).iloc[:9]

row0  column1    180895.00000
      column0    179319.00000
      column3    130734.00000
      column2     94962.00000
row1  column1     90447.50000
      column0     89659.50000
      column3     65367.00000
row2  column1     60298.33333
      column0     59773.00000

答案 2 :(得分:0)

pandas具有一个名为nlargest的函数,该函数将按序列返回任何列的最大值。 [docs]

如果只需要每个索引,则可以使用index.values [usage] [docs],也可以按照docs中的建议使用.index.array

如果要计算所有最大值,请查看this answer here

答案 3 :(得分:0)

这是使用np + collections.Counter的解决方案,它对于获取Counter对象应该非常快。

from collections import Counter
import numpy as np
import pandas as pd

c = Counter(np.tile(df.columns, df.shape[0])[np.argsort(df.to_numpy().ravel())[-9:]])
#Counter({'column0': 3, 'column1': 3, 'column2': 1, 'column3': 2})

s = pd.Series(c).reindex(df.columns).fillna(0).astype(int)
#column0    3
#column1    3
#column2    1
#column3    2
#column4    0
#dtype: int32