使用groupby()从后面进行累积乘法

时间:2019-07-04 20:37:06

标签: pandas

我尝试通过ID对后分组进行列率的累积乘积。

class Box { public int Length { get; set; } public int Height { get; set; } public int Width { get; set; } public int Volume => Length * Width * Height; public void DisplayBox() { Console.WriteLine("The height of box is length {0} * height {1} * width {2} and volume is {3}", Length, Height, Width, Volume); } public Box(){} public Box(int length, int height, int width) { Length = length; Height = height; Width = width; } } class Program { static void Main(string[] args) { //Using custom constructor new Box(5,10,4).DisplayBox(); //Using default constructor new Box {Length = 5, Height = 10, Width = 4}.DisplayBox(); //Using class instance var box = new Box(); box.Length = 5; box.Height = 10; box.Width = 4; box.DisplayBox(); Console.ReadKey(); } }

初始数据框

df.groupby(['id'])['rate'].apply(lambda x: x * x.shift(-1))

更多详细信息

data = {'id': [100, 100, 100, 100, 100, 200, 200, 300], 
        'year':  [2010, 2013, 2014, 2015, 2016, 2010, 2012, 2008],
        'rate':  [0.1, 0.2, 0.1, 0.1, 0.1, 0.1, 0.2, 0.1],
        'tval': [10, 10, 10, 10, 10, 90, 90, 100]}

df = pd.DataFrame(data) 

目标

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试:

df['result'] = (df.groupby('id').rate
                  .transform(lambda x: x[::-1].cumprod()[::-1])
               )

输出:

    id  year  rate  tval   result
0  100  2010   0.1    10  0.00002
1  100  2013   0.2    10  0.00020
2  100  2014   0.1    10  0.00100
3  100  2015   0.1    10  0.01000
4  100  2016   0.1    10  0.10000
5  200  2010   0.1    90  0.02000
6  200  2012   0.2    90  0.20000
7  300  2008   0.1   100  0.10000