简体   繁体   English

Python:使用取决于先前值的值填充数据框中的列

[英]Python: Populate column in data frame with a value that depends on the previous value

i need to find a concise way to populate my dataframe with code like the following:我需要找到一种简洁的方法来使用如下代码填充我的 dataframe:

x = 1
df.at[x,'col2']=df.at[x,'col1'] + df.at[x-1,'col2']
x = 2
df.at[x,'col2']=df.at[x,'col1'] + df.at[x-1,'col2']
x = 3
df.at[x,'col2']=df.at[x,'col1'] + df.at[x-1,'col2']
x = 4
df.at[x,'col2']=df.at[x,'col1'] + df.at[x-1,'col2']

... and so on til the final rows. ...等等,直到最后几行。 Each line of code depends on the result of the one above so I am not sure if it can use the rolling function?每行代码都取决于上面的结果,所以我不确定它是否可以使用滚动 function? I have also tried .shift(1) but haven't been successful either.我也尝试过.shift(1)但也没有成功。 Basically I need to compute this above from x=1 to x=last column基本上我需要计算上面从 x=1 到 x=last 列

Take the following as an example:以下面为例:

       col1         col2
0       0             0
1       1           value above (0) plus value from col1 (1) = 1
2       3           value above (1) plus value from col1 (3) = 4 

Can anyone help?谁能帮忙?

A quick solution, it could be made better by making it generic (this is specific to the question)一个快速的解决方案,可以通过使其通用来做得更好(这是特定于问题的)

import pandas as pd
d = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
df = pd.DataFrame(data=d)
print(df,"\n\n")
x = len(df)
df.iloc[1:,1] = df.iloc[1:x,0].values + df.iloc[0:x-1,1].values

print(df)

I used.values to get a round the problem of the index giving NaNs and was helped by this post which ran into the same problems.我使用 .values 来解决索引给出 NaN 的问题,并得到了遇到同样问题的这篇文章的帮助。

This returns,这返回,

   col1  col2
0     1     4
1     2     5
2     3     6 


   col1  col2
0     1     4
1     2     6
2     3     8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM