How to copy numpy array value to higher sizes

I have a (w, h) np array in 2d. I want to make a 3D measurement whose value is greater than 1 and copy its value along 3 dimensions. I was hoping the broadcast would do this, but that was not possible. This is how i do it

arr = np.expand_dims(arr, axis=2)
arr = np.concatenate((arr,arr,arr), axis=2)

is there a faster way to do this?

+8
source share
6 answers

You can move all the dimming forward by entering a single dimming / new axis as the last dimming to create an 3Darray, and then repeating three times along this using , for example, like this: np.repeat

arr3D = np.repeat(arr[...,None],3,axis=2)

Here's another approach using - np.tile

arr3D = np.tile(arr[...,None],3)
+6

, :

x_train = np.stack((x_train,) * 3, axis=-1)

+4

- , :

a=np.random.randn(4,4)    #a.shape = (4,4)
a = np.expand_dims(a,-1)  #a.shape = (4,4,1)
a = a*np.ones((1,1,3))
a.shape                   #(4, 4, 3)
+2

a- 3- .

img3 = np.zeros((gray.shape[0],gray.shape[1],3))
img3[:,:,0] = gray
img3[:,:,1] = gray
img3[:,:,2] = gray
fig = plt.figure(figsize = (15,15))
plt.imshow(img3)
+1

, , , :

>>> a = numpy.array([[1,2], [3,4]])
>>> c = numpy.zeros((4, 2, 2))
>>> c[0] = a
>>> c[1:] = a+1
>>> c
array([[[ 1.,  2.],
        [ 3.,  4.]],

       [[ 2.,  3.],
        [ 4.,  5.]],

       [[ 2.,  3.],
        [ 4.,  5.]],

       [[ 2.,  3.],
        [ 4.,  5.]]])
0

barebones numpy.concatenate() , , :

# sample 2D array to work with
In [51]: arr = np.random.random_sample((12, 34))

# promote the array 'arr' to 3D and then concatenate along 'axis 2'
In [52]: arr3D = np.concatenate([arr[..., np.newaxis]]*3, axis=2)

# verify for desired shape
In [53]: arr3D.shape
Out[53]: (12, 34, 3)

, . (: ):

In [42]: %timeit -n 100000 np.concatenate([arr[..., np.newaxis]]*3, axis=2)
1.94 µs ± 32.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [43]: %timeit -n 100000 np.repeat(arr[..., np.newaxis], 3, axis=2)
4.38 µs ± 46.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [44]: %timeit -n 100000 np.dstack([arr]*3)
5.1 µs ± 57.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [49]: %timeit -n 100000 np.stack([arr]*3, -1)
5.12 µs ± 125 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [46]: %timeit -n 100000 np.tile(arr[..., np.newaxis], 3)
7.13 µs ± 85.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

, , :

# wrap your 2D array in an iterable and then multiply it by the needed depth
arr3D = np.dstack([arr]*3)

# verify shape
print(arr3D.shape)
(12, 34, 3)
0

Source: https://habr.com/ru/post/1654419/


All Articles