简体   繁体   中英

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!

尝试这个:

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

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

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