熊猫:根据百分位条件过滤数据框

时间:2017-07-11 17:30:37

标签: python-2.7 pandas percentile

我有一个数据框df,其中包含按网页浏览量(PV)排名的一些基本网络统计信息:

URL  PVs
1    1500
2    1200
3    900
4    700
:
100  25

我正在尝试过滤和计算导致不同百分位页面浏览量(PV)的网址数量。说,我想知道有多少以及哪些URL带来了90%的PV(或10%)。

我计算了百分位数:

df.quantile(np.linspace(.1, 1, 9, 0))

而且我知道我可以遍历这样的行(所以我可以总结一下):

for index, row in df.iterrows():
    print row['PVs']

但我无法弄清楚当达到某个阈值时如何停止。非常感谢您的帮助!

2 个答案:

答案 0 :(得分:4)

我认为您需要按条件计算sumTrue个值:

a = (df['PVs'] > df['PVs'].quantile(0.9)).sum()
print (a)
1
df1 = df[df['PVs'] > df['PVs'].quantile(0.9)]
print (df1)
   URL   PVs
0    1  1500
a = (df['PVs'] < df['PVs'].quantile(0.1)).sum()
print (a)
1
df1 = df[df['PVs'] < df['PVs'].quantile(0.1)]
print (df1)
   URL  PVs
4  100   25

如果需要计算所有分位数:

df1 = df.groupby(pd.qcut(df['PVs'], 10)).size()
print (df1)
PVs
(24.999, 295.0]     1
(295.0, 565.0]      0
(565.0, 740.0]      1
(740.0, 820.0]      0
(820.0, 900.0]      1
(900.0, 1020.0]     0
(1020.0, 1140.0]    0
(1140.0, 1260.0]    1
(1260.0, 1380.0]    0
(1380.0, 1500.0]    1
dtype: int64

答案 1 :(得分:3)

考虑一系列网址

s = pd.Series(np.random.randint(100, size=10000), name='URL')

使用pd.Series.value_counts获取计数列表并使用normalize=True选项。另外,请务必使用ascending=True

对升序进行排序
vc = s.value_counts(normalize=True, ascending=True)

vc现在是索引中URL s的系列,并将counts标准化为值。因为它按升序排序,我们可以执行累计求和并在您要查找的断点处挑选项目的位置。

a = vc.cumsum().searchsorted(np.linspace(.1, 1, 9, 0))

vc.index[a]

Int64Index([64, 40, 20, 18, 9, 45, 67, 30, 77], dtype='int64')

我们可以观察结果

a = vc.cumsum().searchsorted(np.linspace(.1, 1, 9, 0))
pd.concat([vc.cumsum().iloc[a], vc.iloc[a]], axis=1, keys=['Cumsum', 'Normalized'])

    Cumsum  Normalized
64  0.1075      0.0089
40  0.2083      0.0094
20  0.3036      0.0096
18  0.4010      0.0099
9   0.5010      0.0101
45  0.6032      0.0103
67  0.7084      0.0106
30  0.8049      0.0108
77  0.9053      0.0114
相关问题