如何使用特定的索引顺序重塑 numpy 数组?

我正在尝试将一些数组重塑为特定的顺序,但numpy.reshape并没有解决我的问题,除非我真的必须使用,否则我不想使用任何循环。


让我们以一个a带有值的数组为例:


a = [['x1','x2','x3','y1','y2','y3','z1','z2','z3'],

['x4','x5','x6','y4','y5','y6','z4','z5','z6']]

并np.reshape(a,[-1,18])返回:


array([['x1', 'x2', 'x3', 'y1', 'y2', 'y3', 'z1', 'z2', 'z3', 

     'x4', 'x5','x6', 'y4', 'y5', 'y6', 'z4', 'z5', 'z6']], dtype='<U2')

但是否有可能得到这样的结果:


[['x1', 'x2', 'x3','x4', 'x5','x6', 'y1', 'y2', 'y3','y4', 'y5', 'y6',

 'z1', 'z2', 'z3', 'z4', 'z5', 'z6']]


慕容森
浏览 200回答 2
2回答

幕布斯7119047

您需要重塑和转置数组:import numpy as npa = np.array([['x1','x2','x3','y1','y2','y3','z1','z2','z3'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ['x4','x5','x6','y4','y5','y6','z4','z5','z6']])b = a.reshape(2, 3, 3).transpose((1, 0, 2)).ravel()print(b)# ['x1' 'x2' 'x3' 'x4' 'x5' 'x6' 'y1' 'y2' 'y3' 'y4' 'y5' 'y6' 'z1' 'z2'#&nbsp; 'z3' 'z4' 'z5' 'z6']一步一步,首先你有你的初始数组。print(a)# [['x1' 'x2' 'x3' 'y1' 'y2' 'y3' 'z1' 'z2' 'z3']#&nbsp; ['x4' 'x5' 'x6' 'y4' 'y5' 'y6' 'z4' 'z5' 'z6']]然后将其重塑为“两个 3x3 矩阵”:print(a.reshape(2, 3, 3))# [[['x1' 'x2' 'x3']#&nbsp; &nbsp;['y1' 'y2' 'y3']#&nbsp; &nbsp;['z1' 'z2' 'z3']]##&nbsp; [['x4' 'x5' 'x6']#&nbsp; &nbsp;['y4' 'y5' 'y6']#&nbsp; &nbsp;['z4' 'z5' 'z6']]]现在,如果您将其展平,x3那么您将获得y1. 您需要对轴重新排序,以便在x3go之后x4,这意味着您首先要迭代列 ( x1, x2, x3),然后跳转到下一个矩阵以迭代其第一行 ( x4, x5, x6) 中的列,然后继续到下一行第一个矩阵。所以最里面的维度应该是相同的(列),但是你必须交换前两个维度,所以你首先改变矩阵,然后改变行而不是相反:print(a.reshape(2, 3, 3).transpose((1, 0, 2)))# [[['x1' 'x2' 'x3']#&nbsp; &nbsp;['x4' 'x5' 'x6']]##&nbsp; [['y1' 'y2' 'y3']#&nbsp; &nbsp;['y4' 'y5' 'y6']]##&nbsp; [['z1' 'z2' 'z3']#&nbsp; &nbsp;['z4' 'z5' 'z6']]]现在可以将其展平以获得所需的结果。print(a.reshape(2, 3, 3).transpose((1, 0, 2)).ravel())# ['x1' 'x2' 'x3' 'x4' 'x5' 'x6' 'y1' 'y2' 'y3' 'y4' 'y5' 'y6' 'z1' 'z2'#&nbsp; 'z3' 'z4' 'z5' 'z6']

冉冉说

如果x,y和z值的长度相同,则可以使用以下方法np.array_split将结果展平.ravel():np.array(np.array_split(a, 3, axis=1)).ravel()array(['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'y1', 'y2', 'y3', 'y4', 'y5',&nbsp; &nbsp; &nbsp; &nbsp;'y6', 'z1', 'z2', 'z3', 'z4', 'z5', 'z6'], dtype='<U2')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python