Skip to main content
 首页 » 编程设计

python之将 DataFrame 的列设置为 pandas 中另一个列的总和

2025年05月04日14Free-Thinker

我有一个如下所示的 DataFrame,称之为“值”:

我想创建另一个,称之为“sums”,它包含从“sums”中的列到末尾的 DataFrame“值”的总和。它看起来像下面这样:

我想在不逐个数据点查看整个 DataFrame 的情况下创建它。我一直在尝试使用 .apply() 如下所示,但我不断收到错误消息:unsupported operand type(s) for +: 'int' and 'datetime.date'

In [26]: values = pandas.DataFrame({0:[96,54,27,28], 
              1:[55,75,32,37],2:[54,99,36,46],3:[35,77,0,10],4:[62,25,0,25], 
              5:[0,66,0,89],6:[0,66,0,89],7:[0,0,0,0],8:[0,0,0,0]}) 
 
In [28]: sums = values.copy() 
 
In [29]: sums.iloc[:,:] = ''          
 
In [31]: for column in sums: 
    ...:     sums[column].apply(sum(values.loc[:,column:])) 
    ...:      
Traceback (most recent call last): 
 
  File "<ipython-input-31-030442e5005e>", line 2, in <module> 
    sums[column].apply(sum(values.loc[:,column:])) 
  File "C:\WinPython64bit\python-3.5.2.amd64\lib\site-packages\pandas\core\series.py", line 2220, in apply 
    mapped = lib.map_infer(values, f, convert=convert_dtype) 
  File "pandas\src\inference.pyx", line 1088, in pandas.lib.map_infer (pandas\lib.c:63043) 
 
TypeError: 'numpy.int64' object is not callable 
 
 
In [32]: for column in sums: 
    ...:     sums[column] = sum(values.loc[:,column:]) 
 
In [33]: sums 
Out[33]:  
    0   1   2   3   4   5   6   7  8 
0  36  36  35  33  30  26  21  15  8 
1  36  36  35  33  30  26  21  15  8 
2  36  36  35  33  30  26  21  15  8 
3  36  36  35  33  30  26  21  15  8 

有没有办法不用单独循环每个点来做到这一点?

请您参考如下方法:

无需循环,您可以反转数据帧,每行 cumsum 然后重新反转它:

>>> values.iloc[:,::-1].cumsum(axis=1).iloc[:,::-1] 
     0    1    2    3    4    5   6  7  8 
0  302  206  151   97   62    0   0  0  0 
1  462  408  333  234  157  132  66  0  0 
2   95   68   36    0    0    0   0  0  0 
3  324  296  259  213  203  178  89  0  0