简体   繁体   中英

Create a new dataframe column as a product of all the rows of another column

I have the below dataframe:

   a
0  1
1  2
2  3
3  4

I am looking to create a new column 'b' such as the value of the row i of 'b' is defined as the product of all the previous rows of 'a', minus 1:

row_b(i) = row_a(i)*row_a(i-1)*row_a(i-2)*...*row_a(0) - 1

As a result:

  • The first row of 'b' is 1 -1 =0
  • The second row of 'b' is 2 * 1 -1 = 1
  • The third row of 'b' is 3 * 2 * 1 -1 =5
  • etc.

In such a way that the final dataframe looks like:

   a   b
0  1   0
1  2   1
2  3   5
3  4  23

I am looking for the most pythonic and less computationally intensive way to perform this operations.

Thank you for your help Z

As mentioned by @Quang Hong, the answer is simply

df['a'].cumprod()-1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM