我需要帮助将 Matlab find() 语句转换为 Python

I need help converting Matlab find() statement to Python

在Matlab中计算了以下指标:

index = find(the(:) == lat & phi(:) == lon & ~isnan(dat(:)));

所有数组的大小都相同。我正在尝试转换此索引以便在 python 中使用并添加另一个参数。这是我目前所拥有的:

index = np.argwhere((the[:] == lat) & (phi[:] == lon) & (~np.isnan(dat[:])) & (start <= tim[:] <= stop))

想法是使用这个索引来查找数组中满足索引中条件的所有值。当我尝试使用我制作的 Python 版本时,它 returns 错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我还没有让 a.all() 或 a.any() 工作。我需要使用这些吗?如果是这样,在这种情况下我该如何正确使用它们?

您可以关注 NumPy for Matlab users 页面。

  • NumPy the[:] 不等同于 MATLAB the(:),你可以使用 the.flatten()
  • NumPy 中的
  • & 按位应用 AND,请改用 logical_and
  • 而不是 argwhere,使用 nonzero

您没有 post 任何输入数据样本,因此发明了一些输入数据(用于测试)。

这是 Python 代码:

from numpy import array, logical_and, logical_not, nonzero, isnan, r_

# MATLAB code:
#the = [1:3; 4:6];
#lat = 3;
#phi = [5:7; 6:8];
#dat = [2, 3; 5, 4; 4, 6];
#lon = 7;
#index = find(the(:) == lat & phi(:) == lon & ~isnan(dat(:)));

# https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html
the = array([r_[1:4], r_[4:7]])
lat = 3
phi = array([r_[5:8], r_[6:9]])
dat = array([[2, 3], [5, 4], [4, 6]])
lon = 7

index = nonzero(logical_and(logical_and(the.flatten() == lat, phi.flatten() == lon), logical_not(isnan(dat.flatten()))))