【问题标题】:Reshape 2D numpy array into 3 1D arrays with x,y indices将 2D numpy 数组重塑为 3 个具有 x,y 索引的 1D 数组
【发布时间】:2022-01-21 14:38:35
【问题描述】:

我有一个充满值的 numpy 二维数组 (50x50)。我想将二维数组展平为一列(2500x1),但这些值的位置非常重要。索引可以转换为空间坐标,所以我想要另外两个 (x,y) (2500x1) 数组,这样我就可以检索相应值的 x,y 空间坐标。

例如:

My 2D array: 
--------x-------
[[0.5 0.1 0. 0.] |
 [0. 0. 0.2 0.8] y
 [0. 0. 0. 0. ]] |

My desired output: 
#Values
[[0.5]
 [0.1]
 [0. ]
 [0. ]
 [0. ]
 [0. ]
 [0. ]
 [0.2]
 ...], 
#Corresponding x index, where I will retrieve the x spatial coordinate from
[[0]
 [1]
 [2]
 [3]
 [4]
 [0]
 [1]
 [2]
 ...], 
#Corresponding y index, where I will retrieve the x spatial coordinate from
[[0]
 [0]
 [0]
 [0]
 [1]
 [1]
 [1]
 [1]
 ...], 

关于如何做到这一点的任何线索?我已经尝试了一些方法,但没有奏效。

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    为了简单起见,让我们用这段代码重现你的数组:

    value = np.arange(6).reshape(2, 3)
    

    首先,我们创建变量 x, y,其中包含每个维度的索引:

    x = np.arange(value.shape[0])
    y = np.arange(value.shape[1])
    

    np.meshgrid 是方法,与您描述的问题有关:

    xx, yy = np.meshgrid(x, y, sparse=False)
    

    最后,用这些线将所有元素转换成你想要的形状:

    xx = xx.reshape(-1, 1)
    yy = yy.reshape(-1, 1)
    value = value.reshape(-1, 1)
    

    【讨论】:

      【解决方案2】:

      根据你的例子,np.indices:

      data = np.arange(2500).reshape(50, 50)
      y_indices, x_indices = np.indices(data.shape)
      

      重塑您的数据:

      data = data.reshape(-1,1)
      x_indices = x_indices.reshape(-1,1)
      y_indices = y_indices.reshape(-1,1)
      
      

      【讨论】:

        【解决方案3】:

        假设您想要展平并重塑为单列,请使用reshape

        a = np.array([[0.5, 0.1, 0., 0.],
                      [0., 0., 0.2, 0.8],
                      [0., 0., 0., 0. ]])
        
        a.reshape((-1, 1)) # 1 column, as many row as necessary (-1)
        

        输出:

        array([[0.5],
               [0.1],
               [0. ],
               [0. ],
               [0. ],
               [0. ],
               [0.2],
               [0.8],
               [0. ],
               [0. ],
               [0. ],
               [0. ]])
        
        获取坐标
        y,x = a.shape
        np.tile(np.arange(x), y)
        # array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3])
        np.repeat(np.arange(y), x)
        # array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2])
        

        或者干脆使用unravel_index:

        Y, X = np.unravel_index(range(a.size), a.shape)
        # (array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]),
        #  array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]))
        

        【讨论】:

        • 谢谢你,你知道我如何对空间坐标做同样的事情吗?
        • @user3611 当然,请参阅编辑
        • 索引部分使用np.unravel_index(range(a.size), a.shape)比较简单
        • @bb1 谢谢,很好!我会更新答案!
        • 谢谢大家的帮助!这些有效!
        猜你喜欢
        • 2016-06-30
        • 2016-02-10
        • 2023-03-14
        • 2020-04-22
        • 2017-12-01
        • 1970-01-01
        • 2017-09-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多