Python还原累积矩阵

时间:2014-12-03 11:19:42

标签: python matrix cumsum

我有一个像这样的矩阵

[[1,2,4,6],
[4,7,9,9],
[1,9,10,20]]

我如何通过python中的列获得部分总和?

[[1,2,4,6],
[(4-1),(7-2),(9-4),(9-6)],
[(1-4),(9-7),(10-9),(20-9)]]

5 个答案:

答案 0 :(得分:1)

从第二行开始,您想要的只是行i和行i-1的区别,第一行只是原始数组的第一行。最简单的方法是使用numpy。所以这有效:

In [1]: import numpy as np

In [2]: a = np.array( [[1,2,4,6],
   ...: [4,7,9,9],
   ...: [1,9,10,20]]
   ...: )

In [3]: np.vstack( (a[0], a[1:]-a[:-1]) )
Out[3]: 
array([[ 1,  2,  4,  6],
       [ 3,  5,  5,  3],
       [-3,  2,  1, 11]])

正如亨利沃顿勋爵(!)指出,差异a[1:]-a[:-1]np.diff(a, axis=0)相同。

答案 1 :(得分:1)

如果你想要一个不涉及numpy的解决方案,只使用列表和itertools.tee(内置),那么下面应该可以使用

from itertools import tee

a = [[1,2,4,6],
     [4,7,9,9],
     [1,9,10,20]]

b = []
b.append(a[0])

# Create two iterators and advance one once.
x, y = tee(a)
next(y)

# Iterate over your two iterators and construct a list t which is their difference
# then append this list to b
for i, j in zip(x, y):
  t = [h-g for g, h in zip(i,j)]
  b.append(t)

print(b)
# [[1, 2, 4, 6], 
#  [3, 5, 5, 3], 
#  [-3, 2, 1, 11]]

答案 2 :(得分:1)

尝试

np.vstack((Z[0],np.diff(Z,axis=0)))

其中Z是您要区分的矩阵。

答案 3 :(得分:0)

如果您不想使用 numpy itertools ,则代码为

>>> a=[[1,2,4,6],
... [4,7,9,9],
... [1,9,10,20]]
>>> a_r = a[::-1]  # reverse original list
>>> for i in range(len(a_r)-1):
...    for j in range(len(a_r[0])):
...       a_r[i][j] = a_r[i][j] - a_r[i+1][j]
... 
>>> a=a_r[::-1]  # reverse result 
>>> for i in a: print i
[1, 2, 4, 6]
[3, 5, 5, 3]
[-3, 2, 1, 11]

答案 4 :(得分:0)

我认为这个很好

>>> a = [[1,2,4,6],
... [4,7,9,9],
... [1,9,10,20]]
>>> c = [[0]*5] ; c.extend(a)
>>> print [[ s-r for r, s in zip(*t)] for t in zip(c[:-1],c[1:])]
[[1, 2, 4, 6], [3, 5, 5, 3], [-3, 2, 1, 11]]
>>> 

这里我在列表列表中添加了一个零列表(获取c),并通过使用zip进行一些打包和解包,我有一个包含预期结果的列表列表。 / p>