Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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.]])
share|improve this answer
    
Really useful answer. Thanks –  Mattijn Jun 6 '13 at 13:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.