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!
CodePudding user response:
Try this:
df["C"] = df["B"].shift().fillna(df.loc[0, "A"]).cumprod()
CodePudding user response:
This will work if you don't have a large df
data = {'A' : [0.1, 0.1, 0.1, 0.1, 0.1],
'B' : [1.66, 1.66, 1.66, 1.66, 1.66]}
df = pd.DataFrame(data)
df.at[0, 'C'] = df.iloc[0]['A']
for i in range(1, len(df)):
df.at[i, 'C'] = df.iloc[i-1]['B'] * df.iloc[i-1]['C']
df