Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.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,我想在python中的pandas中的数据帧上应用cumsum,但不带零。我只想在数据帧上保留零并执行cumsum。假设我有这样的数据帧: import pandas as pd df = pd.DataFrame({'a' : [1,2,0,1], 'b' : [2,5,0,0], 'c' : [0,1,2,5]}) a b c 0 1 2 0 1 2 5 1 2 0 0 2

我想在
python
中的
pandas
中的数据帧上应用
cumsum
,但不带零。我只想在数据帧上保留零并执行
cumsum
。假设我有这样的数据帧:

import pandas as pd

df =  pd.DataFrame({'a' : [1,2,0,1], 
                    'b' : [2,5,0,0], 
                    'c' : [0,1,2,5]})

   a  b  c
0  1  2  0
1  2  5  1
2  0  0  2
3  1  0  5
结果应该是

   a  b  c
0  1  2  0
1  3  7  1
2  0  0  3
3  4  0  8

有没有办法避免循环?在
R
中有
ave
函数,但我对
python
非常陌生,我不知道。

您可以屏蔽df,以便只覆盖非零单元格:

In [173]:
df[df!=0] = df.cumsum()
df

Out[173]:
   a  b  c
0  1  2  0
1  3  7  1
2  0  0  3
3  4  0  8

太简单了,不能看太多,下次我会努力想办法解决。如果我的答案解决了你的问题,那么你应该接受它,这样问题就不会一直没有答案了,谢谢