Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 添加一列作为具有条件的其他列的总和_Python_Pandas - Fatal编程技术网

Python 添加一列作为具有条件的其他列的总和

Python 添加一列作为具有条件的其他列的总和,python,pandas,Python,Pandas,我需要编写一个代码来创建新的列B,嵌入第一列a的总和 当累计值小于0时,B中的值应为0 然后cumsum再次开始,直到下一个值在a上建立一个循环并得到总数。如果总数小于0,则将其设置为0。然后把新的总数加在B后面 你有一个a=[1,…],总数=0,B=[] total = 0 B = [] for i in range(len(A)): # process the sum total += A[i] if total < 0: total = 0

我需要编写一个代码来创建新的列B,嵌入第一列a的总和

当累计值小于0时,B中的值应为0


然后cumsum再次开始,直到下一个值在a上建立一个循环并得到总数。如果总数小于0,则将其设置为0。然后把新的总数加在B后面

你有一个
a=[1,…]
,总数=0,B=[]

total = 0
B = []
for i in range(len(A)):
   # process the sum
    total += A[i]
    if total < 0:
        total = 0
    B.append(total)
total=0
B=[]
对于范围内的i(len(A)):
#处理总数
总计+=A[i]
如果总数<0:
总数=0
B.追加(总数)

这里是一个非参数答案,它通过迭代循环a列中的值,并通过从不低于0来创建B列

result = []
cur_res = 0
for i in df.A:
    cur_res = max(cur_res + i, 0)
    result.append(cur_res)

df['B'] = result

我刚刚在jupyter笔记本中做了如下修改:result=[]cur_res=0,用于df['A']中的I:cur_res=max(cur_res+I,0)result.append(cur_res)df['B']=result,它可以工作。谢谢!
result = []
cur_res = 0
for i in df.A:
    cur_res = max(cur_res + i, 0)
    result.append(cur_res)

df['B'] = result