【问题标题】:Python: How to calculate a cumulative sum of a dataframe column? [duplicate]Python:如何计算数据框列的累积总和? [复制]
【发布时间】: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

【问题讨论】:

  • 不 - 我不需要列的累积总和 - 请查看最终结果数据框,因为这正是我需要的

标签: python pandas dataframe


【解决方案1】:
df = pd.DataFrame({"ts1":[0, 3, 2, 5]})
df['ts2'] = df.ts1.cumsum()

【讨论】:

    猜你喜欢
    • 2021-09-03
    • 2015-06-29
    • 2021-10-31
    • 2017-10-05
    • 2021-12-07
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多