python - Pandas groupby 加温均值
问题描述
正常的 groupby 平均值很容易:
df.groupby(['col_a','col_b']).mean()[col_i_want]
但是,如果我想应用一个 winsorized 平均值(默认限制为 0.05 和 0.95),这相当于裁剪数据集然后执行平均值,突然似乎没有简单的方法可以做到这一点?我必须:
winsorized_mean = []
col_i_want = 'col_c'
for entry in df['col_a'].unique():
for entry2 in df['col_b'].unique():
sub_df = df[(df['col_a'] == entry) & (df['col_b'] == entry2)]
m = sub_df[col_to_groupby].clip(lower=0.05,upper=0.95).mean()
winsorized_mean.append([entry,entry2,m])
有没有我不知道的自动执行此操作的功能?
解决方案
您可以使用scipy.stats.trim_mean:
import pandas as pd
from scipy.stats import trim_mean
# label 'a' will exhibit different means depending on trimming
label = ['a'] * 20 + ['b'] * 80 + ['c'] * 400 + ['a'] * 100
data = list(range(100)) + list(range(500, 1000))
df = pd.DataFrame({'label': label, 'data': data})
grouped = df.groupby('label')
# trim 5% off both ends
print(grouped.apply(stats.trim_mean, .05))
# trim 10% off both ends
print(grouped.apply(stats.trim_mean, .1))
推荐阅读
- linux - gz文件的递归grep从输出字符串中搜索字符串
- r - 需要使用 Rmarkdown 创建源,否则会出现错误消息
- javascript - 提交后如何编辑x-editable值
- c++ - 初始化指向另一个结构内的结构的指针
- javascript - Angular 2+检测服务内的对象属性变化
- php - 两个 PHP 实例(在 Apache 中)可以共享同一个 PDO 持久连接吗?
- c++ - 如何在 UE4 / C++ 中可视化我的四叉树
- android - 将 Realm 实体移动到另一个包
- java - Cloud Firestore 安全规则权限
- css - 有没有办法让网格布局中的孩子用 CSS 拉伸全宽