2

Assume dst is an ndarray with shape (5, N), and ramp is an ndarray with shape (5,). (In this case, N = 2):

>>> dst = np.zeros((5, 2))
>>> dst
array([[0., 0.],
       [0., 0.],
       [0., 0.],
       [0., 0.],
       [0., 0.]])
>>> ramp = np.linspace(1.0, 2.0, 5)
>>> ramp
array([1.  , 1.25, 1.5 , 1.75, 2.  ])

Now I'd like to copy ramp into the columns of dst, resulting in this:

>>> dst
array([[1., 1.],
       [1.25., 1.25.],
       [1.5., 1.5.],
       [1.75, 1.75],
       [2.0, 2.0]])

I didn't expect this to work, and it doesn't:

>>> dst[:] = ramp
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (5) into shape (5,2)

This works, but I'm certain there's a more "numpyesque" way to accomplish this:

>>> dst[:] = ramp.repeat(dst.shape[1]).reshape(dst.shape)
>>> dst
array([[1.  , 1.  ],
       [1.25, 1.25],
       [1.5 , 1.5 ],
       [1.75, 1.75],
       [2.  , 2.  ]]) 

Any ideas?

note

Unlike "Cloning" row or column vectors, I want to assign ramp into dst (or even a subset of dst). In addition, the solution given there uses a python array as the source, not an ndarray, and thus requires calls to .transpose, etc.

2
  • Does this answer your question? "Cloning" row or column vectors Commented Mar 9, 2020 at 23:37
  • The suggested post (stackoverflow.com/questions/1550130/…) ends up being much more complex than the answer given below. And it doesn't address copying into a vector. I never would have discovered this "nump-ish" technique otherwise. Commented Mar 10, 2020 at 0:00

1 Answer 1

1

Method 1: Use broadcasting:

As OP mentioned in the comment. Broadcasting works on assigment too

dst[:] = ramp[:,None]

Method 2: Use column_stack

N = dst.shape[1]
dst[:] = np.column_stack([ramp.tolist()]*N)

Out[479]:
array([[1.  , 1.  ],
       [1.25, 1.25],
       [1.5 , 1.5 ],
       [1.75, 1.75],
       [2.  , 2.  ]])

Method 3: use np.tile

N = dst.shape[1]
dst[:] = np.tile(ramp[:,None], (1,N))
Sign up to request clarification or add additional context in comments.

2 Comments

Ah! Thank you for the ramp[:,None] hint. This is even easier (since broadcasting works in this case): dst[:] = ramp[:,None]. (If you agree, feel free to update your answer!)
hah! totally forgot about broadcasting works on assignment too. I added it to the answer :)

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.