Search code examples
pythonpandasdataframemultiplication

Create new dataframe column keeping the first value from another column


I have a dataframe with two columns

import pandas as pd

df = pd.DataFrame()
df['A'] = [0.1, 0.1, 0.1, 0.1, 0.1]
df['B'] = [1.66, 1.66, 1.66, 1.66, 1.66]
  A    B
0.1 1.66
0.1 1.66
0.1 1.66
0.1 1.66
0.1 1.66

I want to create a new column where I hold the first value of column A and then complete the rest of column values as following:

  A     B          C
0.1  1.66       A[0]
0.1  1.66  B[0]*C[0]
0.1  1.66  B[1]*C[1]
0.1  1.66  B[2]*C[2]
0.1  1.66  B[3]*C[3] 

staying this way

   A   B       C
1.66 0.1     0.1
1.66 0.1   0.166
1.66 0.1 0.27556
1.66 0.1 0.45743
1.66 0.1 0.75933

Is there any way to achieve this? ... thanks in advance!


Solution

  • Try this:

    df["C"] = df["B"].shift().fillna(df.loc[0, "A"]).cumprod()