Assigning values to two dimensional array from two one dimensional ones

Question:

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

output:

[[ 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.

Asked By: Cupitor

||

Answers:

How about 2 lines?

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

And the proof it works:

>>> 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.]])
Answered By: mgilson

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.

So:

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 3×1-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))
Answered By: abarnert

If you insist on 1 line, use fancy indexing:

>>> a[:,0],a[:,1]=[1,1,1],[1,2,3]
Answered By: dawg
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.