1

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.

  • post a dataframe showing the orginal form, and another dataframe showing the expected output. Use this as a guide : https://www.google.com/search?q=pandas+minimal+example+stackoverflow&oq=pandas+minim&aqs=chrome.1.0j69i59j69i57j69i59j0l3j69i60.9004j0j7&sourceid=chrome&ie=UTF-8 – sammywemmy Feb 08 '20 at 14:54
  • 1
    Use [`shift`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shift.html) to create another column offset by 1 so that they're on the same row – roganjosh Feb 08 '20 at 14:58
  • Where is the data, the [mcve]? – AMC Feb 08 '20 at 18:22
  • Also, this is a blatant duplicate of https://stackoverflow.com/q/34855859/11301900. – AMC Feb 08 '20 at 18:23

1 Answers1

1

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
ansev
  • 30,322
  • 5
  • 17
  • 31