Andrade Andrade - 25 days ago 9
Python Question

Add each list element to beginning of each row in numpy matrix (python)

I am just learning how to use the numpy matrix function and I am running into a problem.

I have a list of n integers, and a matrix of n rows. I need to add each number from the list to the beginning of its corresponding row in the matrix.

So if I have the following matrix and list:

m = np.matrix([[0, 13], [13, 0]])
myList = [10, 11]


My desired output is this:

newMatrix = [[10, 0, 13],
[11, 13, 0]]


Here's the code I have so far (trying to replicate the last example on this page):

for c in range(len(myList)):
newMatrix = np.insert(m[c],[0],myList[c])


But this of course only gives the last iteration of the for loop ([11, 13, 0]). I would like to somehow append each row to a new matrix but I can't seem to figure that out.

EDIT: The length of the list and the matrix will not always be known.

If anyone more experienced with numpy matrices knows a better way to do this, I would really appreciate it! Thanks in advance.

Answer

One option is to reshape your myList and then use np.concatenate() function:

import numpy as np

np.concatenate((np.array(myList).reshape(len(myList),1), m), axis = 1)
# matrix([[10,  0, 13],
#         [11, 13,  0]])

You can also do:

np.concatenate((np.array(myList)[:, None], m), axis = 1)

# matrix([[10,  0, 13],
#         [11, 13,  0]])
Comments