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

时间:2019-02-14 14:38:32

标签: python 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']]

2 个答案:

答案 0 :(得分:1)

您需要keyreshape数组:

import numpy as np

a = np.array([['x1','x2','x3','y1','y2','y3','z1','z2','z3'],
              ['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'
#  'z3' 'z4' 'z5' 'z6']

一步一步,首先要有初始数组。

print(a)
# [['x1' 'x2' 'x3' 'y1' 'y2' 'y3' 'z1' 'z2' 'z3']
#  ['x4' 'x5' 'x6' 'y4' 'y5' 'y6' 'z4' 'z5' 'z6']]

然后将其重塑为“两个3x3矩阵”:

print(a.reshape(2, 3, 3))
# [[['x1' 'x2' 'x3']
#   ['y1' 'y2' 'y3']
#   ['z1' 'z2' 'z3']]
#
#  [['x4' 'x5' 'x6']
#   ['y4' 'y5' 'y6']
#   ['z4' 'z5' 'z6']]]

现在,如果您将其展平,则在x3之后,您将得到y1。您需要重新排列轴,以便在x3进入x4之后,这意味着您首先要迭代列(x1x2x3),然后跳转到下一个矩阵以迭代其第一行中的列(x4x5x6),然后继续到第一矩阵的下一行。因此,最里面的尺寸应该是相同的(列),但是您必须交换前两个尺寸,因此您首先要更改矩阵,然后更改行,而不是相反:

print(a.reshape(2, 3, 3).transpose((1, 0, 2)))
# [[['x1' 'x2' 'x3']
#   ['x4' 'x5' 'x6']]
#
#  [['y1' 'y2' 'y3']
#   ['y4' 'y5' 'y6']]
#
#  [['z1' 'z2' 'z3']
#   ['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'
#  'z3' 'z4' 'z5' 'z6']

答案 1 :(得分:1)

如果xyz的长度相同,则可以使用np.array_split并用.ravel()展平结果:< / p>

np.array(np.array_split(a, 3, axis=1)).ravel()

array(['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'y1', 'y2', 'y3', 'y4', 'y5',
       'y6', 'z1', 'z2', 'z3', 'z4', 'z5', 'z6'], dtype='<U2')