Numpy reshape an array with specific order

人盡茶涼 提交于 2021-02-17 04:26:25

问题


Let's say I have this array x:

x = array([1, 2, 3, 4, 5, 6, 7, 8])
x.shape = (8,1)

I want to reshape it to become

array([[1, 3, 5, 7], 
       [2, 4, 6, 8]])

this is a reshape(2, 4) on x but in the straight forward way:

y = x.reshape(2,4)

y becomes

array([[1, 2, 3, 4],
       [5, 6, 7, 8]])

and that's not what I want. Is there a way to transform the array in that specific way?


回答1:


In[4]: x.reshape(4, 2).T
Out[4]: 
array([[1, 3, 5, 7],
       [2, 4, 6, 8]])



回答2:


The easiest way to do this is to specify the orderargument in reshape function.


You need the Fortran order.

Side note: Matlab by default is using Fortran order but in python you need to specify that.


Use this:

x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = x.reshape(2,4, order='F')

print(y)
#array([[1, 3, 5, 7],
#       [2, 4, 6, 8]])



回答3:


Another option is to use the option order='F' to your reshape-call like

res = numpy.reshape(my_array, (2,4), order='F')

https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.reshape.html




回答4:


Yes, you can do:

y = np.array([x[0::2], x[1::2]])


来源:https://stackoverflow.com/questions/52969468/numpy-reshape-an-array-with-specific-order

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