PythonPandas:找到前n,然后在前n中找到m

2024-06-09 10:43:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据框,如下所示:

fastmoving[['dist','unique','id']]
Out[683]: 
        dist  unique          id
1   0.406677     4.0  4.997434e+09
2   0.406677     4.0  4.452593e+09
5   0.406677     4.0  4.188395e+09
1   0.434386     4.0  8.288070e+09
4   0.434386     4.0  3.274609e+09

我想实现的是:

  1. 查找前n个最长距离条目。“dist”列
  2. 查找在前n个条目中具有最大百分比m的ID。列“id”。你知道吗

到目前为止,我能够为最大的条目编写代码。你知道吗

#Get the first id with the largest dist:
fastmoving.loc[fastmoving['dist'].idxmax(),'id']

#Get all id's with the largest dist:
fastmoving.loc[fastmoving['dist']==fastmoving['dist'].max(),'id']

我怀念的是我的代码为多个值工作。你知道吗

  1. 所以不是最大值,而是一系列的最大值(top n值)。

  2. 然后得到在那些n最大值中超过某个m百分比的所有id。

你能帮助我怎样在熊猫身上做到这一点吗?你知道吗

多谢了 亚历克斯


Tags: the数据代码idgetdistwith条目
2条回答

IIUC,你可以利用^{}。下面的示例将取dist的top3值,并从中提取id的top2值:

fastmoving.nlargest(3, ["dist", "id"]).nlargest(2, "id")
       dist  unique            id
1  0.434386     4.0  8.288070e+09
1  0.406677     4.0  4.997434e+09

可以使用^{}表示顶n,使用^{}表示顶m%,如下所示:

import pandas as pd
from io import StringIO

fastmoving = pd.read_csv(StringIO("""
        dist  unique          id
1   0.406677     4.0  4.997434e+09
2   0.406677     4.0  4.452593e+09
5   0.406677     4.0  4.188395e+09
1   0.434386     4.0  8.288070e+09
4   0.434386     4.0  3.274609e+09"""), sep="\s+")

n = 3
m = 50

top_n_dist = fastmoving.nlargest(n, ["dist"])
top_m_precent_id_in_top_n_dist = top_n_dist[top_n_dist['id']>top_n_dist['id'].quantile(m/100)]

print(top_m_precent_id_in_top_n_dist)

相关问题 更多 >