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

avi*_*iss 2 percentile python-2.7 pandas

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

URL  PVs
1    1500
2    1200
3    900
4    700
:
100  25
Run Code Online (Sandbox Code Playgroud)

我正在尝试过滤和计算造成不同页面浏览量(PV)百分比的URL数量。说,我想知道有多少个网址带来了90%的PV(或10%)。

我计算了百分位数:

df.quantile(np.linspace(.1, 1, 9, 0))
Run Code Online (Sandbox Code Playgroud)

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

for index, row in df.iterrows():
    print row['PVs']
Run Code Online (Sandbox Code Playgroud)

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

jez*_*ael 5

我认为您需要按条件sumTrue值进行计数:

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

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

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
Run Code Online (Sandbox Code Playgroud)