如何创建running total并在每次出现NaN时重新启动它?

2024-10-02 14:16:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在每次遇到nan的时候发布一个新的跑步总量 例如,从所附图片中,它将对前3个值进行求和[1242536, 379759, 1622295],然后显示运行总数3244590.0,然后从第5个值开始计算新的运行总数,直到第9个值,显示这些值的总和,依此类推。我想将这些运行总计放在这些NaN值旁边的新列中

Example

我曾尝试以以下方式处理这个问题:

for i in df['Budget_Expenditure_2012_']:
        if np.isnan(i) == True:
            x = pd.Index(df['Budget_Expenditure_2012_']).get_loc(i)

    
print(x)

for item in range(0, len(x) - 1, 2):
    second_list.append([x[item],x[item + 1]])    
print(second_list)

其思想是找到每对行之间的值之和。这一对将是需要求和的每个范围的起始位置和最后位置。 在这一点上,我不知道如何执行这个求和操作


Tags: indffornanitem跑步listbudget
2条回答

使用这段代码,您可以在一个名为“总计”的新列上获取每个nan的“运行总计”

total = 0
df['Totals'] = 0 # assign 0 initially to all rows of the new column

for i in range(df.shape[0]): # shape[0] return number of rows

    expenditure = df.loc[i+1, 'Budget_Expenditure_2012_'] # i+1 coz your indexing starts at 1

    if np.isnan(expenditure):
        df.loc[i, 'Totals'] = total
        total = 0
    else:
        total += expenditure

使用shiftisnacumsum的组合来gropuby,然后transform,最后在列为nan的位置分配结果值

df.loc[df['Budget_Expenditure_2012_'].isna(), 'new_column'] = (
    df.groupby(
        df.Budget_Expenditure_2012_.shift()
                                   .isna()
                                   .cumsum()
    )['Budget_Expenditure_2012_'].transform('sum')
)

相关问题 更多 >

    热门问题