简体   繁体   English

创建一个新的 dataframe 列作为另一列的所有行的乘积

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

I have the below dataframe:我有以下 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:我正在寻找创建一个新列'b',例如'b'的第i行的值被定义为'a'的所有先前行的乘积,减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 'b' 的第一行是 1 -1 =0
  • The second row of 'b' is 2 * 1 -1 = 1 'b' 的第二行是 2 * 1 -1 = 1
  • The third row of 'b' is 3 * 2 * 1 -1 =5 'b' 的第三行是 3 * 2 * 1 -1 =5
  • etc.等等

In such a way that the final dataframe looks like:这样最终的 dataframe 看起来像:

   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.我正在寻找最 Pythonic 且计算量较少的方式来执行此操作。

Thank you for your help Z谢谢你的帮助Z

As mentioned by @Quang Hong, the answer is simply正如@Quang Hong所提到的,答案很简单

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 pandas:通过将 DataFrame 行与另一个 DataFrame 的列进行比较来创建新列 - pandas: Create new column by comparing DataFrame rows with columns of another DataFrame 将数据框中的列的行创建为另一个数据框中的列 - Create rows of a column in a dataframe as a column in another dataframe 根据另一个 dataframe 中匹配值的行数创建新列 - Create new column based on number of rows matching value in another dataframe Pandas 数据框根据另一列的条件创建新行 - Pandas dataframe create new rows based on condition from another column 如何从另一列的所有值创建新的列名并按 pandas dataframe 中的另一列创建新列名? - how to create new column names from another column all values and agg by another column in pandas dataframe? 创建一个新列,详细说明一个 PySpark dataframe 中的行是否与 dataframe 的另一列中的行匹配 - Create a new column that details if rows in one PySpark dataframe matches a a row in another column of a dataframe pandas:通过比较DataFrame的一列的DataFrame行来创建新列 - pandas: Create new column by comparing DataFrame rows of one column of DataFrame 循环遍历 dataframe 的行,创建一个新列并根据条件将结果存储在另一列中 - Loop through rows of a dataframe, create a new column and store the result based on condition in another column 如何基于另一个DataFrame中的列在Pandas DataFrame中创建新列? - How to create a new column in a Pandas DataFrame based on a column in another DataFrame? 根据来自另一个熊猫数据框的列在熊猫数据框中创建新行 - Create new rows in a Pandas Dataframe based on a column from another pandas dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM