1

Something I can't figure out by reading the Python documentation and stackoverflow. Probably I'm thinking in the wrong direction..

Let's say I've a predefined 2D Numpy array as follow:

a = np.zeros(shape=(3,2)) 
print a
array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])

Now I would like to populate each column of this 2D array with a 1D data array (one by one), as in:

b = np.array([1,2,3])

# Some code, that I just can't figure out. I've studied insert, column_stack, 
# h_stack, append. Nothing seems to do what I need

print a
array([[ 1.,  0.],
       [ 2.,  0.],
       [ 3.,  0.]])

c = np.array([4,5,6])

# Some code, that I just can't figure out. I've studied insert, column_stack, 
# h_stack, append. Nothing seems to do what I need

print a
array([[ 1.,  4.],
       [ 2.,  5.],
       [ 3.,  6.]])

Any suggestions would be appreciated!

1 Answer 1

1

You can assign to columns with slicing:

>>> a[:,0] = b
>>> a
array([[ 1.,  0.],
       [ 2.,  0.],
       [ 3.,  0.]])

To assign them all at once instead of one at a time, use np.column_stack:

>>> np.column_stack((b, c))
array([[1, 4],
       [2, 5],
       [3, 6]])

If you need it back in the same array, rather than just having the same name, you can assign to a slice containing the whole matrix (as is common with lists):

>>> a[:] = np.column_stack((b, c))
>>> a
array([[ 1.,  4.],
       [ 2.,  5.],
       [ 3.,  6.]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.