I have a numpy multidimensional array array with the following format:
a = [[1,2],
[8,9]]
Then I want to add a list with 3 values (e.g. [4,5,6]
at the end horizontally and vertically with the following result:
a = [[1,2,4],
[8,9,5],
[4,5,6]]
Do I need to combine row_stack and column_stack somehow?
Here is a way using hstack
and vstack
:
>>> a = [[1,2],
... [8,9]]
>>> x = np.array([4, 5, 6])
>>> b = np.vstack((a, x[:-1]))
>>> print np.hstack((b, x[:, None]))
[[1 2 4]
[8 9 5]
[4 5 6]]
You can combine this into one line:
>>> print np.hstack((np.vstack((a, x[:-1])), x[:, None]))
[[1 2 4]
[8 9 5]
[4 5 6]]
Not sure whether there's a better way (i.e. a one-liner), but you could just do this:
z = np.zeros((3,3))
z[:2,:2] = a
z[:,2] = z[2,:] = array([4, 5, 6])
I have a numpy multidimensional array array with the following format:
a = [[1,2],
[8,9]]
Then I want to add a list with 3 values (e.g. [4,5,6]
at the end horizontally and vertically with the following result:
a = [[1,2,4],
[8,9,5],
[4,5,6]]
Do I need to combine row_stack and column_stack somehow?
Here is a way using hstack
and vstack
:
>>> a = [[1,2],
... [8,9]]
>>> x = np.array([4, 5, 6])
>>> b = np.vstack((a, x[:-1]))
>>> print np.hstack((b, x[:, None]))
[[1 2 4]
[8 9 5]
[4 5 6]]
You can combine this into one line:
>>> print np.hstack((np.vstack((a, x[:-1])), x[:, None]))
[[1 2 4]
[8 9 5]
[4 5 6]]
Not sure whether there's a better way (i.e. a one-liner), but you could just do this:
z = np.zeros((3,3))
z[:2,:2] = a
z[:,2] = z[2,:] = array([4, 5, 6])
0 commentaires:
Enregistrer un commentaire