Saturday, March 23, 2019

2DMatrix Operations through List Comprehensions : Python

In python matrix operations can be done through ‘NumPy’ package. But if you need a rudimentary 2D matrix with lists, you could do the matrix operations through “Python List Comprehensions”

eg: Assume you’ve the below matrix representation with list

self.matrix = [["Person/Stock","Product1", "Product2","Product3"],
 ["John",100, 20, 30],
 ["Keith",20, 40, 10],
 ["Russel",20, 60, 20]]

Rowwise Sum can by taken by the below expression:

   [
list(rowSum) for rowSum in
zip([rowName[0] for rowName in self.matrix[1:]],[sum(row[1:]) for row in self.matrix[1:]])
]

Columnwise Sum can be taken by the below expression:

   [
    list(colSum) for colSum in
    zip(self.matrix[0][1:],
    [sum([row[col] for row in self.matrix[1:]]) for col in range(1,len(self.matrix[0]))]
    )
]


You can find more details on GitHub here.