python - (Python,数据帧): Record the average of all numbers in a column that are smaller than the n'th percentile

标签 python pandas dataframe

我有一个类似于下面的 DataFrame,并且想创建一个看起来更像第二个表的 DataFrame 或系列。

例如:我会找到 A 列的第 n 个百分位数,然后取 A 中小于第 n 个百分位数的所有数字的平均值。

我使用下面的代码来获取每列的平均值和范围,但似乎缺少一些东西来获取条件平均值。

min = df.min(axis='index')

max = df.max(axis='index')

mean = df.mean(axis = 'index')

df[df < np.percentile(df, 0.4)].mean()

这似乎不起作用,我相信给出了每行的平均值

表1

Date    A   B   C   D   E   F
02/10/2017  10  5   1   2   1   1
01/10/2017  10  4   9   4   3   5
30/09/2017  4   8   5   6   2   4
29/09/2017  8   2   7   9   10  5
28/09/2017  3   8   2   7   10  8
27/09/2017  7   3   8   9   9   7
26/09/2017  4   1   2   9   3   4
25/09/2017  10  1   6   6   3   5
24/09/2017  8   3   5   5   6   7
23/09/2017  7   9   5   7   1   3
22/09/2017  2   9   10  5   8   1

表2

Index   Avg<40th Percentile
A   3.25
B   1.333333333
C   1.666666667
D   4
E   1.333333333
F   1.666666667

最佳答案

使用

df.where(df < df.quantile(0.4)).mean()

Date         NaN
A       3.250000
B       1.333333
C       1.666667
D       4.000000
E       1.333333
F       1.666667

关于python - (Python,数据帧): Record the average of all numbers in a column that are smaller than the n'th percentile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46530990/

相关文章:

python - 将具有 1 个逗号分隔字符串的列表转换为二维列表

python - 将 @commit_on_success 嵌套在 @commit_manually 中

python - pandas:快速计算具有某些值的列的总和

python - Pandas :将一个数据框的特定列连接到另一个数据框

python - 在Python中将Dataframe写入和读取文件的正确方法

python - 在 pandas 中的特定行之后查找满足条件的下一个第一行

python - 如何更改pyplot轴的增量

python - 我如何获得 opencv 中所有对象的所有像素?

python - 如何将特定列从数据框写入Excel?

r - 计算数据框中自开始以来的月数