Asignación de valores a una matriz bidimensional a partir de dos unidimensionales

Most probably somebody else already asked this but I couldn't find it. The question is how can I assign values to a 2D array from two 1D arrays. For example:

import numpy as np
#a is the 2D array. b is the 1D array and should be assigned 
#to second coordinate. In this exaple the first coordinate is 1.
a=np.zeros((3,2))
b=np.asarray([1,2,3])
c=np.ones(3)
a=np.vstack((c,b)).T

salida:

[[ 1.  1.]
 [ 1.  2.]
 [ 1.  3.]]

I know the way I am doing it so naive, but I am sure there should be a one line way of doing this.

P.S. In real case that I am dealing with, this is a subarray of an array, and therefore I cannot set the first coordinate from the beginning to one. The whole array's first coordinate are different, but after applying np.where they become constant.

preguntado el 27 de noviembre de 13 a las 01:11

3 Respuestas

¿Qué tal 2 líneas?

>>> c = np.ones((3, 2))
>>> c[:, 1] = [1, 2, 3]

Y la prueba de que funciona:

>>> c
array([[ 1.,  1.],
       [ 1.,  2.],
       [ 1.,  3.]])

Or, perhaps you want np.column_stack:

>>> np.column_stack(([1.,1,1],[1,2,3]))
array([[ 1.,  1.],
       [ 1.,  2.],
       [ 1.,  3.]])

respondido 27 nov., 13:01

Thanks. Vote up, but the point is my first array is fixed but not for all values. So in real scenario I am actually using np.where and therefore the first value is 1, otherwise all the coords of first vector are not 1. Algunos son 0 as well. But thanks I will update it. - cupidor

First, there's absolutely no reason to create the original zeros array that you stick in a, never reference, and replace with a completely different array with the same name.

Second, if you want to create an array the same shape and dtype as b but with all ones, use ones_like.

De modo que:

b = np.array([1,2,3])
c = np.ones_like(b)
d = np.vstack((c, b).T

You could of course expand b to a 3x1-array instead of a 3-array, in which case you can use hstack instead of needing to vstack then transpose… but I don't think that's any simpler:

b = np.array([1,2,3])
b = np.expand_dims(b, 1)
c = np.ones_like(b)
d = np.hstack((c, b))

respondido 27 nov., 13:01

If you insist on 1 line, use indexación elegante:

>>> a[:,0],a[:,1]=[1,1,1],[1,2,3]

Respondido el 09 de enero de 23 a las 21:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.