cha*_*sen 5 python arrays numpy
这是我正在努力实现的目标的一个示例。我对 python 很陌生,已经搜索了几个小时来找出我做错了什么。我一直无法找到我的问题是什么。我还很新,可能会搜索错误的短语。如果是这样,您能指出我正确的方向吗?
我想将 n 个数组组合成一个数组。我希望将 x 中的第一行作为组合中的第一行,将 y 中的第一行作为组合中的第二行,将 z 中的第一行作为组合中的第三行,将 x 中的第二行作为组合中的第四行结合起来等等,所以我看起来像这样。
x = [x1 x2 x3]
[x4 x5 x6]
[x7 x8 x9]
y = [y1 y2 y3]
[y4 y5 y6]
[y7 y8 y9]
x = [z1 z2 z3]
[z4 z5 z6]
[z7 z8 z9]
combined = [x1 x2 x3]
[y1 y2 y3]
[z1 z2 z3]
[x4 x5 x6]
[...]
[z7 z8 z9]
Run Code Online (Sandbox Code Playgroud)
我能想到的最好的就是
import numpy as np
x = np.random.rand(6,3)
y = np.random.rand(6,3)
z = np.random.rand(6,3)
combined = np.zeros((9,3))
for rows in range(len(x)):
combined[0::3] = x[rows,:]
combined[1::3] = y[rows,:]
combined[2::3] = z[rows,:]
print(combined)
Run Code Online (Sandbox Code Playgroud)
这一切所做的就是将输入数组的最后一个值写入输出数组中的每第三行,而不是我想要的。我不确定这是否是最好的方法。任何建议都会有所帮助。
*我只是发现这可行,但如果有人知道更高性能的方法,*请告诉我。
import numpy as np
x = np.random.rand(6,3)
y = np.random.rand(6,3)
z = np.random.rand(6,3)
combined = np.zeros((18,3))
for rows in range(6):
combined[rows*3,:] = x[rows,:]
combined[rows*3+1,:] = y[rows,:]
combined[rows*3+2,:] = z[rows,:]
print(combined)
Run Code Online (Sandbox Code Playgroud)
我稍微改变了你的代码以获得所需的输出
import numpy as np
x = np.random.rand(6,3)
y = np.random.rand(6,3)
z = np.random.rand(6,3)
combined = np.zeros((18,3))
combined[0::3] = x
combined[1::3] = y
combined[2::3] = z
print(combined)
Run Code Online (Sandbox Code Playgroud)
您的组合矩阵的形状错误,并且实际上不需要 for 循环。