LWZ*_*LWZ 30 python arrays zip numpy
例如,我有2个数组
a = array([[0, 1, 2, 3],
[4, 5, 6, 7]])
b = array([[0, 1, 2, 3],
[4, 5, 6, 7]])
Run Code Online (Sandbox Code Playgroud)
我怎么能zip
a
和b
这样我得到
c = array([[(0,0), (1,1), (2,2), (3,3)],
[(4,4), (5,5), (6,6), (7,7)]])
Run Code Online (Sandbox Code Playgroud)
?
Dan*_*iel 34
你可以使用dstack:
>>> np.dstack((a,b))
array([[[0, 0],
[1, 1],
[2, 2],
[3, 3]],
[[4, 4],
[5, 5],
[6, 6],
[7, 7]]])
Run Code Online (Sandbox Code Playgroud)
如果你必须有元组:
>>> np.array(zip(a.ravel(),b.ravel()), dtype=('i4,i4')).reshape(a.shape)
array([[(0, 0), (1, 1), (2, 2), (3, 3)],
[(4, 4), (5, 5), (6, 6), (7, 7)]],
dtype=[('f0', '<i4'), ('f1', '<i4')])
Run Code Online (Sandbox Code Playgroud)
对于Python 3+,您需要扩展zip
迭代器对象.请注意,这非常低效:
>>> np.array(list(zip(a.ravel(),b.ravel())), dtype=('i4,i4')).reshape(a.shape)
array([[(0, 0), (1, 1), (2, 2), (3, 3)],
[(4, 4), (5, 5), (6, 6), (7, 7)]],
dtype=[('f0', '<i4'), ('f1', '<i4')])
Run Code Online (Sandbox Code Playgroud)