python numpy:沿新轴扩展数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2357686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
numpy: extending arrays along a new axis?
提问by Duncan Tait
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.
我有一个 (9,4) 数组,我想沿着第三个轴重复它 4096 次......所以它变成了简单的 (9,4,4096),来自 9,4 数组的每个值简单地重复了 4096 次沿着新的轴。
If my dubious 3D diagram makes sense (the diagonal is a z-axis)
如果我可疑的 3D 图有意义(对角线是 z 轴)
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.
编辑:只是为了澄清,这里的重点是为新轴的 4096 个“行”中的每一行重复 (9,4) 数组。想象一个横截面 - 每个原始 (9,4) 数组都是 4096 长方体中的一个。
采纳答案by Steve Tjoa
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
如果X
仅作为 (9,4) 提供给您,则
import scipy
X = scipy.rand(9,4)
Y = X.reshape(9,4,1).repeat(4096,2)
回答by Paul
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)
回答by DavidS
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)