从数据框架计算当前、最小、最大、月平均增长

2024-04-24 03:57:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似于下面的数据集:

product_ID month amount_sold
1          1     23          
1          2     34          
1          3     85          
2          1     47          
2          2     28          
2          3     9           
3          1     73          
3          2     84          
3          3     12          

我希望输出如下:

例如,对于产品1:

-avg_monthly_growth计算公式为((85-34)/34*100+(34-23)/23*100)/2=98.91%

-lowest_monthly_growth是(34-23)/23*100)=47.83%

-highest_monthly_growth是(85-34)/34*100)=150%

-current_monthly_growth是最近两个月之间的增长(在本例中,是从第2个月到第3个月的增长,因为每个产品的month范围为1-3)

product_ID avg_monthly_growth lowest_monthly_growth highest_monthly_growth current_monthly_growth
1          98.91%             47.83%                150%                   150%
2          ...                ...                   ...                    ...
3          ...                ...                   ...                    ...

我试过df.loc[df.groupby('product_ID')['amount_sold'].idxmax(), :].reset_index()得到最大值(同样也得到最小值),但我不太确定如何得到增长百分比。你知道吗


Tags: 数据iddf产品currentproductamountavg
1条回答
网友
1楼 · 发布于 2024-04-24 03:57:14

您可以在axis=1上使用带有h pct_change()pivot_table,然后用所需序列创建字典并创建df:

m=df.pivot_table(index='product_ID',columns='month',values='amount_sold').pct_change(axis=1)
d={'avg_monthly_growth':m.mean(axis=1)*100,'lowest_monthly_growth':m.min(1)*100,
   'highest_monthly_growth':m.max(1)*100,'current_monthly_growth':m.iloc[:,-1]*100}
final=pd.DataFrame(d)
print(final)

             avg_monthly_growth  lowest_monthly_growth  highest_monthly_growth  \
product_ID                                                                      
1                    98.913043              47.826087              150.000000   
2                   -54.141337             -67.857143              -40.425532   
3                   -35.322896             -85.714286               15.068493   

            current_monthly_growth  
product_ID                          
1                       150.000000  
2                       -67.857143  
3                       -85.714286  

相关问题 更多 >