2 回答
TA贡献1794条经验 获得超8个赞
您需要重塑和转置数组:
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. 您需要对轴重新排序,以便在x3go之后x4,这意味着您首先要迭代列 ( x1, x2, x3),然后跳转到下一个矩阵以迭代其第一行 ( x4, x5, x6) 中的列,然后继续到下一行第一个矩阵。所以最里面的维度应该是相同的(列),但是你必须交换前两个维度,所以你首先改变矩阵,然后改变行而不是相反:
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']
TA贡献1877条经验 获得超1个赞
如果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',
'y6', 'z1', 'z2', 'z3', 'z4', 'z5', 'z6'], dtype='<U2')
添加回答
举报