简体   繁体   中英

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

I have a pandas column "A" that reads like below.

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

By using apply(), I need to create a new column "B" by using the below formula.

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

and so on. The problem is I need to refer to the previous cells of the same column to calculate the values for the new column.

Please help.

Use Series.pct_change()

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

Example

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

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