我有如下数据。它是 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/