【发布时间】:2020-08-24 10:01:04
【问题描述】:
我的数据框目前如下所示:
ts1 ts2
0 0 NaN
1 3 NaN
2 2 NaN
3 5 NaN
.... 以此类推到第 1000 行
我需要使用从 x=1 到 x=1000 的以下代码填充 ts2 列。有人可以告诉我如何通过使用 for 循环来简化它吗?
df.at[0,'ts2']=0 #start ts2 row 0 at 0
x = 1
df.at[x,'ts2']=df.at[x,'ts1'] + df.at[x-1,'ts2']
x = 2
df.at[x,'ts2']=df.at[x,'ts1'] + df.at[x-1,'ts2']
x = 3
df.at[x,'ts2']=df.at[x,'ts1'] + df.at[x-1,'ts2']
x = 4
df.at[x,'ts2']=df.at[x,'ts1'] + df.at[x-1,'ts2']
#.....
#x = 1000
#df.at[x,'ts2']=df.at[x,'ts1'] + df.at[x-1,'ts2']
df
我尝试将所有 NaN 替换为 0,并使用以下代码但没有运气:
for x in range(1,1000):
df.at[x,'ts2']=df.at[x,'ts1'] + df.at[x-1,'ts2']
我希望最终结果如下所示:
ts1 ts2
0 0 0
1 3 3 #3+0
2 2 5 #2+3
3 5 10 #5+5
【问题讨论】:
-
不 - 我不需要列的累积总和 - 请查看最终结果数据框,因为这正是我需要的