python - 在python中聚合 Pandas 数据时如何计算每组尾部的总和|均值|中位数

标签 python pandas pandas-groupby tail

我有如下数据。它是 pandas 数据帧格式。

A  B  C  D  E  F  G
1  1  2  3  1  4  2
1  1  2  4  5  6  7
1  1  2  3  2  3  2
1  1  2  4  5  6  7
2  1  2  3  2  3  4
2  1  2  3  4  3  3
2  1  2  4  5  6  7

这里 agg_lvl=['A','B','C']

当数据聚合到 agg_lvl 时,我想通过在每个组中使用 tail(2) 记录来计算 G 变量的均值|中值|和。

我的预期输出是这样的:

均值的预期输出:

A  B  C  G
1  1  2  4.5
2  1  2   5

中值和总和的输出也是相同的,但是我们必须考虑中值和总值来代替均值。

为此,我尝试了以下代码,但没有得到预期的输出。

df.groupby(agg_lvl,as_index=False).tail(2).agg({'G':'mean'})

谁能帮我解决这个问题。

提前致谢。

最佳答案

使用GroupBy.transform代替 agg 返回与 tail 过滤的 DataFrame 具有相同形状的新列:

agg_lvl=['A','B','C']
df = df.groupby(agg_lvl,as_index=False).tail(2)
df['G'] = df.groupby(agg_lvl)['G'].transform('mean')
print (df)
   A  B  C  D  E  F    G
2  1  1  2  3  2  3  4.5
3  1  1  2  4  5  6  4.5
5  2  1  2  3  4  3  5.0
6  2  1  2  4  5  6  5.0

编辑:

df = df.groupby(agg_lvl,as_index=False).tail(2).groupby(agg_lvl,as_index=False)['G'].mean()
print (df)
   A  B  C    G
0  1  1  2  4.5
1  2  1  2  5.0

关于python - 在python中聚合 Pandas 数据时如何计算每组尾部的总和|均值|中位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52183552/

相关文章:

python - numpy 3d 数组 - 选择沿给定轴的最大元素

python - 如何在Python中绘制y轴为 "total of y values corresponding to each x bin"、x轴为n个x的直方图?

python - 如何迭代 Pandas DataFrame 并在另一列中的项目匹配时替换字符串

python - 在数据框中另一列的末尾添加现有列

python - 计算pandas DataFrame中每组的t检验统计量

python - 使用计数比率的附加列对 DataFrame 进行分组和旋转

python - 如何管理大文件?

调用帮助函数时 repr.py 中的 Python 语法错误

Python - 从标记列表到词袋

Pandas groupby 滚动删除索引列