[英]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
列的第一个值,然后完成其余列值,如下所示:
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如果您没有大的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.