Tiago Azevedo Silva
Tiago Azevedo Silva

Reputation: 15

Python revert accumulated matrix

I have a matrix like this

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

how i get the partial sums by columns in python?

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

Upvotes: 0

Views: 86

Answers (5)

gboffi
gboffi

Reputation: 25053

I think this one is nice

>>> 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]]
>>> 

Here I prepend a list of zeros to the list of lists (obtaining c), and by a bit of packing and unpacking using zip I have a list of lists with the expected results.

Upvotes: 0

Irshad Bhat
Irshad Bhat

Reputation: 8709

If you don't want to use numpy or itertools, here is the code

>>> 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]

Upvotes: 0

Andrew Jaffe
Andrew Jaffe

Reputation: 27097

From the second line, what you want is just the difference of row i and row i-1, and the first line is just the first line of the original array. The easiest way to get this is with numpy. So this works:

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]])

As Lord Henry Wotton (!) points out, the difference a[1:]-a[:-1] is the same as np.diff(a, axis=0).

Upvotes: 1

Lord Henry Wotton
Lord Henry Wotton

Reputation: 1362

Try

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

where Z is the matrix you are differentiating.

Upvotes: 1

Ffisegydd
Ffisegydd

Reputation: 53698

If you want a solution that doesn't involve numpy, and just uses list of lists and itertools.tee (which is builtin), then the below should work

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]]

Upvotes: 1

Related Questions