python - 第一行的累积减法

标签 python algorithm pandas math matrix

我有一个系列和一个 DataFrame,都是整数。

s = [10,
     10,
     10]

m = [[0,0,0,0,3,4,5],
     [0,0,0,0,1,1,1],
     [10,0,0,0,0,5,5]]

我想返回一个包含累积差异的矩阵来代替现有数字。

输出:

n = [[10,10,10,10,7,3,-2],
     [10,10,10,10,9,8,7],
     [0,0,0,0,0,-5,-10]]

最佳答案

先逐行计算数据帧的cumsum,然后从Series中减去:

import pandas as pd

s = pd.Series(s) 
df = pd.DataFrame(m)

-df.cumsum(1).sub(s, axis=0)

#    0   1   2   3  4  5   6
#0  10  10  10  10  7  3  -2
#1  10  10  10  10  9  8   7
#2   0   0   0   0  0 -5 -10

关于python - 第一行的累积减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52772018/

相关文章:

python - Numpy seterr 未检测到溢出

python - 删除 pandas DataFrame 打印中的 `dtype: object`

在特定约束条件下找到最佳项目组合的算法

python - 选择文本文件中的特定行和单元格并放入数据框 : python or R

python - 在 wxPython 中调整父级大小时重新缩放图像

python - 使用 Pymongo 插入文档 - InvalidDocument : Cannot encode object

algorithm - 日期类型值的模糊匹配

algorithm - 多维数组之和

python - 在 Pandas GroupBy 数据框中按 ID 计算两个日期之间的行数

python - 将一列json字符串转换成列数据