Pandas基于百分比变化和初始值的新累积列

huangapple go评论70阅读模式
英文:

Pandas new cumulating column based on percentange change and initial value

问题

根据您提供的描述,您想要计算新的"items"列,但没有提供具体的计算方法。如果您需要帮助编写Python代码以在pandas DataFrame中执行此计算,请提供更多细节,以便我可以为您提供准确的代码示例。

英文:

Having an initial dataframe like this, defined with a items columns and a percentage column:
Pandas基于百分比变化和初始值的新累积列

How can I calculate the new items column as shown in the following picture?
Pandas基于百分比变化和初始值的新累积列

In theory this seems an easy task in my mind (and in Excel/Google Sheet), but trying to do this with a pandas dataframe is getting me mad!
Thank you for the help!

答案1

得分: 1

你需要计算累积百分比,方法是除以100,加1,然后计算cumprod,最后乘以"items"列:

df = pd.DataFrame({'label': list('ABCDE'),
                   'items': 5,
                   'perc': [float('nan'), 0, 24.32, -19.57, -91.80]})

df['new_items'] = (df['perc']
                   .fillna(0).div(100).add(1)
                   .cumprod().mul(df['items'])
                  )

输出结果如下:

  label  items   perc  new_items
0     A      5    NaN   5.000000
1     B      5   0.00   5.000000
2     C      5  24.32   6.216000
3     D      5 -19.57   4.999529
4     E      5 -91.80   0.409961

中间结果如下:

  label  items   perc  new_items  percent   cumprod
0     A      5    NaN   5.000000   1.0000  1.000000
1     B      5   0.00   5.000000   1.0000  1.000000
2     C      5  24.32   6.216000   1.2432  1.243200
3     D      5 -19.57   4.999529   0.8043  0.999906
4     E      5 -91.80   0.409961   0.0820  0.081992
英文:

You need to compute the cumulated percentage by dividing by 100, adding 1 and computing the cumprod, then multiply by "items":

df = pd.DataFrame({'label': list('ABCDE'),
                   'items': 5,
                   'perc': [float('nan'), 0, 24.32, -19.57, -91.80]})

df['new_items'] = (df['perc']
                   .fillna(0).div(100).add(1)
                   .cumprod().mul(df['items'])
                  )

Output:

  label  items   perc  new_items
0     A      5    NaN   5.000000
1     B      5   0.00   5.000000
2     C      5  24.32   6.216000
3     D      5 -19.57   4.999529
4     E      5 -91.80   0.409961

Intermediates:

  label  items   perc  new_items  percent   cumprod
0     A      5    NaN   5.000000   1.0000  1.000000
1     B      5   0.00   5.000000   1.0000  1.000000
2     C      5  24.32   6.216000   1.2432  1.243200
3     D      5 -19.57   4.999529   0.8043  0.999906
4     E      5 -91.80   0.409961   0.0820  0.081992

huangapple
  • 本文由 发表于 2023年6月15日 21:09:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76482827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定