Is there a more Pythonic/elegant way to expand the dimensions of a Numpy Array?

倾然丶 夕夏残阳落幕 提交于 2020-01-14 10:32:43

问题


What I am trying to do right now is:

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

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!

Is there a better way to do this?


回答1:


One alternative approach could be with reshaping -

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

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.

Sample run -

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)


来源:https://stackoverflow.com/questions/40069220/is-there-a-more-pythonic-elegant-way-to-expand-the-dimensions-of-a-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!