How to multiply iteratively down a column?

前端 未结 2 1605
长情又很酷
长情又很酷 2021-01-21 11:45

I am having a tough time with this one - not sure why...maybe it\'s the late hour.

I have a dataframe in pandas as follows:

1     10
2     11
3     20
4          


        
相关标签:
2条回答
  • 2021-01-21 11:53

    Use cumprod.

    Example:

    df = pd.DataFrame({'A': [10, 11, 20, 5, 10]}, index=range(1, 6))
    df['cprod'] = df['A'].cumprod()
    
    0 讨论(0)
  • 2021-01-21 12:04

    Note, since your example is just a single column, a cumulative product can be done succinctly with a Series:

    import pandas as pd
    
    s = pd.Series([10, 11, 20, 5, 10])
    s
    
    # Output
    0    10
    1    11
    2    20
    3     5
    4    10
    dtype: int64
    
    s.cumprod()
    
    # Output
    0        10
    1       110
    2      2200
    3     11000
    4    110000
    dtype: int64
    

    Kudos to @bananafish for locating the inherent cumprod method.

    0 讨论(0)
提交回复
热议问题