python - Pandas .apply() : How to use a formula in apply() that involves values from preceding cells in the same column?

标签 python pandas apply

我有一个 pandas 列“A”,如下所示。

A = A1, A2, A3, A4, A5, A6, A7

通过使用 apply(),我需要使用以下公式创建一个新列“B”。

B1 = (A2 - A1)/A1
B2 = (A3 - A2)/A2
B3 = (A4 - A3)/A3

等等。 问题是我需要引用同一列的先前单元格来计算新列的值。

请帮忙。

最佳答案

使用Series.pct_change()

df['B'] = df['A'].pct_change().shift(-1)

示例

df = pd.DataFrame({'A':[1,2,3,4,5]})
print(df)
   A
0  1
1  2
2  3
3  4
4  5


df['B'] = df['A'].pct_change().shift(-1)
print(df)
   A         B
0  1  1.000000
1  2  0.500000
2  3  0.333333
3  4  0.250000
4  5       NaN

关于python - Pandas .apply() : How to use a formula in apply() that involves values from preceding cells in the same column?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60127932/

相关文章:

lisp - 在 Lisp 中应用的参数

r - 通过行组合索引矩阵时避免应用

python - 属性错误: 'module' object has no attribute 'plotting'

python - python属性的get和set顺序是什么?

python - 当键更改并且值是更多键值对时,是否可以对键值对的 JSON 对象进行排序。

python - 按条件替换 pandas 数据框列中的值

python - 如何在pandas中处理这个逻辑

python - 根据一天中的时间选择 DataFrame 中的行?

javascript - 使用 apply 创建一个组合 N 个数组的所有元素的函数

python - Pandas源码导入多个模块