Python中的Zip数组

我有一个2D阵列和一个1D阵列。我想将它们拉在一起。

import numpy as np

arr2D = [[5.88964708e-02, -2.38142395e-01, -4.95821417e-01, -7.07269274e-01], [0.53363666,  0.1654723 , -0.16439857, -0.44880487]]
arr2D = np.asarray(arr2D)

arr1D = np.arange(7, 8.5+0.5, 0.5)
arr1D = np.asarray(arr1D)

res = np.array(list(zip(arr1D, arr2D)))

print(res)

这是结果

[[7.0 array([ 0.05889647, -0.2381424 , -0.49582142, -0.70726927])]
 [7.5 array([ 0.53363666,  0.1654723 , -0.16439857, -0.44880487])]]

但我希望结果像

[[(7.0, 0.05889647), (7.5, -0.2381424), (8.0, -0.49582142), (8.5, -0.70726927)]]
 [[(7.0, 0.53363666), (7.5, 0.1654723),(8.0, -0.16439857), (8.5, -0.44880487)]]

我怎样才能做到这一点?

评论
svero
svero

You can use numpy.tile to expand the 1d array, and then use numpy.dstack, namely:

import numpy as np

arr2D = np.array([[5.88964708e-02, -2.38142395e-01, -4.95821417e-01, -7.07269274e-01], 
                  [0.53363666,  0.1654723 , -0.16439857, -0.44880487]])
arr1D = np.arange(7, 8.5+0.5, 0.5)

np.dstack([np.tile(arr1D, (2,1)), arr2D])
array([[[ 7.        ,  0.05889647],
        [ 7.5       , -0.2381424 ],
        [ 8.        , -0.49582142],
        [ 8.5       , -0.70726927]],

       [[ 7.        ,  0.53363666],
        [ 7.5       ,  0.1654723 ],
        [ 8.        , -0.16439857],
        [ 8.5       , -0.44880487]]])
点赞
评论
99.90%
99.90%

您几乎在那里:

list(map(lambda x: list(zip(arr1D, x)), arr2D))
[[(7.0, 0.0588964708),
  (7.5, -0.238142395),
  (8.0, -0.495821417),
  (8.5, -0.707269274)],
 [(7.0, 0.53363666), (7.5, 0.1654723), (8.0, -0.16439857), (8.5, -0.44880487)]]
点赞
评论