0

I'm not sure if this is called broadcasting or something else, but supposed I'm given a 1-D numpy array of size L. I want to turn this into an n-dimensional numpy array, where one of the dimensions is of size L and the other dimensions are arbitrary, but greater than 0.

e.g., suppose L = 2 and I want to turn this into a n=2-dimensional array of size 2x3 (2 rows, 3 columns), in this case, each row will consist of the original 1-D array.

Is there a function that will allow me to do this in numpy?

1
  • 1
    First reshape it to (2,1). Expanding to (2,3) will be then be easier (and easier to visualize). Commented Feb 18, 2022 at 3:56

1 Answer 1

1

One approach is to use broadcast_to. You could also use the tile function to a similar effect.

import numpy as np

a = np.arange(10)
print('Array before:')
print(a)
print('Array after:')
np.broadcast_to(a,(3,10))

Result:

Array before:
[0 1 2 3 4 5 6 7 8 9]
Array after:

array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
Sign up to request clarification or add additional context in comments.

2 Comments

Ah I think this is it, but why can't I do np.broadcast_to(a,(10,3))? This gives the error ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (10,) and requested shape (10,3)
By the rules of broadcasting, new leading dimensions are automatic, but trailing dimensions have to be explicit. np.broadcast_to(a[:,None],(10,3)). expands a (10,1) to (10,3). Ben's example expands a (10,) to (1,10) to (3,10).

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.