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.

fearless_fool
  • 33,645
  • 23
  • 135
  • 217
  • Does this answer your question? ["Cloning" row or column vectors](https://stackoverflow.com/questions/1550130/cloning-row-or-column-vectors) – AMC Mar 09 '20 at 23:37
  • The suggested post (https://stackoverflow.com/questions/1550130/cloning-row-or-column-vectors) 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. – fearless_fool Mar 10 '20 at 00:00

1 Answers1

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))
fearless_fool
  • 33,645
  • 23
  • 135
  • 217
Andy L.
  • 24,909
  • 4
  • 17
  • 29
  • 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!) – fearless_fool Mar 09 '20 at 23:36
  • hah! totally forgot about broadcasting works on assignment too. I added it to the answer :) – Andy L. Mar 09 '20 at 23:40