开发者

numpy: extending arrays along a new axis?

开发者 https://www.devze.com 2022-12-21 09:32 出处:网络
Surely there must be a way to do this... I can\'t work it out. I have a (9,4) array, and I want to repeat it along a 3rd axis 4096 times... So it becomes simply (9,4,4096), with each value from the 9

Surely there must be a way to do this... I can't work it out.

I have a (9,4) array, and I want to repeat it along a 3rd axis 4096 times... So it becomes simply (9,4,4096), with each value from the 9,4 array simply repeated 4096 times down the new axis.

If my dubious 3D diagram makes sense (the diagonal is a z-axis)

4|   /off to 4096
3|  /
2| /
1|/_ _ _ _ _ _ _ _ _ 
   1 2 3 4 5 6 7 8 9

Cheers

开发者_开发知识库

EDIT: Just to clarify, the emphasis here is on the (9,4) array being REPEATED for each of the 4096 'rows' of the new axis. Imagine a cross-section - each original (9,4) array is one of those down the 4096 long cuboid.


Here is one way:

import scipy
X = scipy.rand(9,4,1)
Y = X.repeat(4096,2)

If X is given to you as only (9,4), then

import scipy
X = scipy.rand(9,4)
Y = X.reshape(9,4,1).repeat(4096,2)


You can also rely on the broadcasting rules to repeat-fill a re-sized array:

import numpy
X = numpy.random.rand(9,4)
Y = numpy.resize(X,(4096,9,4))

If you don't like the axes ordered this way, you can then transpose:

Z = Y.transpose(1,2,0)


Question is super old, but here's another option anyway:

import numpy as np
X = np.random.rand(9,4)
Y = np.dstack([X] * 4096)


A simple numpy solution woudl be using numpy.tile

import numpy as np
a = np.random.rand(9, 4)
b = np.tile(a, (4096, 1, 1))


i think there is a built in numpy function for that called np.full.

a=np.zeros((9,4))
np.full((4096,9,4),a) 

documentation here https://numpy.org/doc/stable/reference/generated/numpy.full.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号