简体   繁体   English

无法使用 np.where() 在复杂的 2D Python 数组中找到元素的索引

[英]Unable to find the index of an element in a complex 2D Python array using np.where()

I am trying to use numpy.where() to find out the index of an element, but it returns an empty array.我正在尝试使用 numpy.where() 来找出元素的索引,但它返回一个空数组。

import numpy as np
grid= np.mgrid[-2:2:5*1j, -2:2:11*1j]
X , Y = grid[0], grid[1]
complex_grid = X+1j*Y
xid, yid= np.where(complex_grid == -1.0 - 0.8j)
print(xid, yid)

It should return index (1,3), but it returns an empty array and its data type.它应该返回索引 (1,3),但它返回一个空数组及其数据类型。 What am I doing wrong?我究竟做错了什么?

EDIT :- My main aim is to find the index corresponding to a given coordinate (x,y) from a grid.编辑 :- 我的主要目标是从网格中找到与给定坐标 (x,y) 相对应的索引。 I made a complex grid just because I can fuse the two 2D matrices I get from mgrid.我制作了一个复杂的网格,因为我可以融合从 mgrid 获得的两个二维矩阵。

Floating point values are seldom exact, so it's generally considered a bad idea to directly compare them.浮点值很少是精确的,因此直接比较它们通常被认为是一个坏主意。

However you can use something like abs(difference) < epsilon to check for a given closeness to a value, for example:但是,您可以使用abs(difference) < epsilon类的东西来检查某个值的给定接近度,例如:

>>> xid, yid= np.where(np.abs(complex_grid -(-1.0 - 0.8j)) < 1e-10)
>>> print(xid, yid)
[1] [3]

or even better: Use numpy.isclose which already does that but allows relative and absolute tolerances and nan handling (if you need these) as well:甚至更好:使用numpy.isclose它已经做到了,但也允许相对和绝对容差以及nan处理(如果你需要这些):

>>> xid, yid= np.where(np.isclose(complex_grid, -1 - 0.8j)))
>>> print(xid, yid)
[1] [3]

isclose()是更好的选择,因为比较浮点数总是很冒险:

xid, yid = np.where(np.isclose(complex_grid, np.ones(complex_grid.shape) * (-1.0 - 0.8j)))

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

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