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.
my solution is:
import numpy as np
m = np.matrix([[0, 13], [13, 0]])
myList = [10, 11]
newmatrix = np.insert(m, 0, myList, axis=1)
the output is:
[[10 0 13]
[11 13 0]]
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]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.