Klem
Klem

Reputation: 59

Extend 1d numpy array in multiple dimensions

I have a 1d numpy array, e.g. a=[10,12,15] and I want to extend it so that I end up with a numpy array b with the shape (3,10,15,20) filled with a so that e.g. b[:,1,1,1] is [10,12,15]. I thought of using np.repeat but it's not clear to me how to do ?

Upvotes: 0

Views: 573

Answers (2)

hpaulj
hpaulj

Reputation: 231355

tile will do it for you. Internally this does a repeat for each axis.

In [114]: a = np.array([10,12,15])
In [115]: A = np.tile(a.reshape(3,1,1,1),(1,10,15,20))
In [116]: A.shape
Out[116]: (3, 10, 15, 20)
In [117]: A[:,1,1,1]
Out[117]: array([10, 12, 15])

For some purposes it might be enough to just do the reshape and let broadcasting expand the dimensions as needed (without actually expanding memory use).

Upvotes: 1

Aaj Kaal
Aaj Kaal

Reputation: 1274

Code:

import numpy as np

a = np.arange(1800).reshape((10,12,15))
b = np.repeat(a, repeats=5, axis=0).reshape(((3,10,15,20)))

You can change axis if you want to repeat in a different fashion. To understand repeat use lower shape for e.g. a(3,5,4) and b (2,3,5,4) and repeat on different axis.

Upvotes: 0

Related Questions