Pandas groupby:将组中的最后一个除以组中的第一个 [英] Pandas groupby: divide last in group by first in group

查看:130
本文介绍了Pandas groupby:将组中的最后一个除以组中的第一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按多列分组的数据框.在每个组中,我想然后生成一个值,用于查找每个组的最后一个实体并除以第一个实体.我还想在输出中显示实体数量和最后一个实体值.

I have a dataframe that I have grouped by multiple columns. Within each group, I would like to then generate a value that finds the last entity of each of those groups and divide by the first entity. I would also like to show the number of entities and the last entity value in the output.

请参阅下面的示例数据和所需的输出.我知道如何显示组的计数,如下代码所示.

See below for an example data and the desired output. I know how to show the count of the group, shown below in the code.

df_group=df.groupby(['ID','Item','End_Date','Type'])
df_output=df_group.size().reset_index(name='Group Count')

下面,我按以下分组:

因此,我正在寻找的示例输出数据帧中的第一行的最终值为 2(该组的最新值),以及最后一个值 2 除以第一个值 3 的百分比变化.还显示了另外两个示例.

So the first row in the example output dataframe that I am seeking has the Final Value of 2 (the most recent value for the group), and a percent change of the last value of 2 divided by the first value of 3. Two more examples are shown as well.

如果您有关于如何将此应用程序处理为 groupby 对象的任何提示,请告诉我.非常感谢您的帮助.

Please let me know if you have any tips on how to go about this application to a groupby object. Thank you very much for your help.

推荐答案

groupby tailhead

df_group=df.groupby(['ID','Item','End_Date','Type'])
df_output=df_group.size().reset_index(name='Group Count')
df_output['PCTCHange']=((df_group.value.tail(1)/df_group.value.head(1))-1).values
df_output['FinalValue']=df_group.value.tail(1).values

这篇关于Pandas groupby:将组中的最后一个除以组中的第一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆