简体   繁体   English

将 numpy inidces 转换为 (N*M) x 2 坐标数组

[英]Convert numpy inidces to (N*M) x 2 array of coordinates

I am trying to get an array containing the indices of every item in a N x M array data as coordinates in the format (N*M) x 2 such that the first column of the array contains row indices and the second column contains column indices for data .我正在尝试获取一个数组,其中包含 N x M 数组data中每个项目的索引作为格式 (N*M) x 2 的坐标,这样数组的第一列包含行索引,第二列包含列索引对于data The length of the resulting array would be N*M so that every item in data as a row.结果数组的长度为 N*M,因此data中的每个项目都为一行。 Alternatively, a list of tuples with coordinate information would also suffice.或者,具有坐标信息的元组列表也足够了。

In:在:

    0   1   2
  -------------
0 | a | b | c |
1 | e | f | g |
2 | h | i | j |
  -------------

Out:出去:

array([0, 0],
      [0, 1],
      [0, 2],
      [1, 0],
      [1, 1],
      [1, 2],
      ...   )

I've only been able to find questions from people making the opposite conversion, unfortunately.不幸的是,我只能从进行相反转换的人那里找到问题。 My ultimate goal is to feed this array into scipy.spatial.distance.cdist() to get the distance of every point from every other point.我的最终目标是将此数组输入 scipy.spatial.distance.cdist() 以获取每个点与其他点的距离。 I am working with [(X,Y) -> Z] raster data, so I can't use cdist on the cell values as it would typically be used .我正在使用 [(X,Y) -> Z] 栅格数据,因此我不能像通常使用的那样对单元格值使用 cdist 。 I'm new to numpy, so this has been a bit of head scratcher.我是 numpy 的新手,所以这有点让人头疼。 I've looked into np.meshgrid, np.column_stack, and np.unravel_index, but I haven't been able to make them work with the output from np.indices.我查看了 np.meshgrid、np.column_stack 和 np.unravel_index,但我无法让它们与 np.indices 中的 output 一起使用。

I think you can do:我认为你可以这样做:

[*zip(*np.where(np.ones_like(a)))]

Output: Output:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

You could use list comprehension .您可以使用list comprehension

M = 3
N = 4

[(i, j) for i in range(N) for j in range(M)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2)]

You can use unravel_index and the shape of the data, it works with individual ints or an array of ints.您可以使用 unravel_index 和数据的形状,它适用于单个整数或整数数组。 In your case, you can get it all in one line with:在您的情况下,您可以通过以下方式获得所有信息:

np.array(np.unravel_index(np.arange(data.size),data.shape)).T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM