有没有更多的Pythonic/优雅方法来扩展Numpy数组的尺寸? [英] Is there a more Pythonic/elegant way to expand the dimensions of a Numpy Array?

查看:298
本文介绍了有没有更多的Pythonic/优雅方法来扩展Numpy数组的尺寸?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在想做的是:

x = x[:, None,  None,  None,  None,  None,  None,  None,  None,  None]

基本上,我想将Numpy数组扩展9个维度.或某些N个维度,其中N可能事先未知!

Basically, I want to expand my Numpy array by 9 dimensions. Or some N number of dimensions where N might not be known in advance!

有更好的方法吗?

推荐答案

另一种方法可能是reshaping-

x.reshape((-1,) + (1,)*N)  # N is no. of dims to be appended

因此,基本上对于与单例尺寸相对应的None's,我们沿这些暗处使用长度为1的形状.对于第一个轴,我们使用-1的形状将所有元素 推入其中.

So, basically for the None's that correspond to singleton dimensions, we are using a shape of length 1 along those dims. For the first axis, we are using a shape of -1 to push all elements into it.

样品运行-

In [119]: x = np.array([2,5,6,4])

In [120]: x.reshape((-1,) + (1,)*9).shape
Out[120]: (4, 1, 1, 1, 1, 1, 1, 1, 1, 1)

这篇关于有没有更多的Pythonic/优雅方法来扩展Numpy数组的尺寸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆