我有一个数据帧,其中有两个实验组,我正在尝试获得百分位数分布。但是,数据已经分组:
df = pd.DataFrame({'group': ['control', 'control', 'control','treatment','treatment','treatment'],
'month': [1,4,9,2,5,12],
'ct': [8,4,2,5,5,7]})
我想计算哪个月份表示每个组的第25、50、75个百分位数,但dataframe已经根据group/month变量进行了分组。
更新1:我意识到我没有澄清我遇到的麻烦。这是一个分组的数据帧,因此,例如,控件具有8个数据点,其中month = 1,4个数据点,其中month = 4,2个数据点,其中month = 9。以下百分位值应为:
x = pd.Series([1,1,1,1,1,1,1,1,4,4,4,4,9,9)]
x.quantile([0.25,0.5,0.75])
>> 0.25 1.0
0.50 1.0
0.75 4.0
dtype: float64
按组分组并取分位数并不能提供准确的答案。有没有一种方法可以分解计数并取未分组的值的百分位数?最终对象应具有以下值:
p25 p50 p75
control 1 1 4
treatment 2 5 12
发布于 2019-02-03 02:08:03
您可以使用Series.repeat
,然后获取分位数:
df.groupby('group').apply(lambda x: (x.month.repeat(x.ct)).quantile([0.25, 0.5, 0.75])).rename_axis([None], axis=1)
0.25 0.50 0.75
group
control 1.0 1.0 4.0
treatment 2.0 5.0 12.0
发布于 2019-02-03 01:52:21
您可以尝试以列表形式使用所需百分比的pd.quanitle
df.groupby('group').quantile([0.25,0.50,0.75])
输出:
ct month
group
control 0.25 3.0 2.5
0.50 4.0 4.0
0.75 6.0 6.5
treatment 0.25 5.0 3.5
0.50 5.0 5.0
0.75 6.0 8.5
发布于 2019-02-03 05:40:53
您可能想要检查describe
df.groupby('group').describe().stack()
https://stackoverflow.com/questions/54495778
复制相似问题