简体   繁体   English

创建新的数据框列,保留另一列的第一个值

[英]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.

相关问题 Python:在数据帧中,创建一个新列,并使用从另一列的值中切出的字符串 - Python: In a dataframe, create a new column with a string sliced from a column with the value of another column 根据另一个 dataframe 的值创建新列 dataframe 运行速度快吗? - create new column of dataframe base on value of another dataframe run fast? 如何使用来自满足条件的另一列的解析值在 dataframe 中创建新列 - How to create a new column in a dataframe with a parsed value from another column where condition is satisfied 如何创建一个新的数据框列,并从另一个列中移出值? - How to create a new dataframe column with shifted values from another column? 如果来自另一个 dataframe 的列和来自原始 dataframe 的列具有匹配值,则在原始 dataframe 中创建一个新列 - Create a new column in the original dataframe if the column from another dataframe and a column from original dataframe have matching values 使用来自另一个数据帧的 if 条件在 Pandas 数据帧中创建一个新列 - create a new column in pandas dataframe using if condition from another dataframe 根据来自另一个数据框的 2 个条件创建新的数据框列 - Create new dataframe column based on 2 criteria from another dataframe 使用数据框列中的键对值创建新列 - Create new column using keys pair value from a dataframe column 如何在 DataFrame 中创建新列并将 select 数据从第一列移动到新列 - How to create a new column in a DataFrame and move select data from the first column to the new column 根据另一个 dataframe 中匹配值的行数创建新列 - Create new column based on number of rows matching value in another dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM