python - 我需要帮助将 Matlab find() 语句转换为 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 版本时,它返回错误:
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 用户页面。
- NumPy
the[:]
不等同于 MATLABthe(:)
,您可以使用the.flatten()
&
在 NumPy 中应用按位与,logical_and
改为使用。- 而不是
argwhere
,使用nonzero
.
您没有发布任何输入数据样本,因此发明了一些输入数据(用于测试)。
这是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()))))
推荐阅读
- mysql - Django Annotate - 来自上次创建的 ManyToMany 对象字段的 Concat
- python - 如何在 disocrd.py 上获得回复消息?
- python - 在 pandas 的滚动窗口中应用 pd.cut
- python - 如何在字典理解中包含 for 循环和 if 语句?
- android - 我正在尝试创建一个用于反应的本机模块,但我在 build.gradle 中发现了一个错误
- scala - 无法解决 scala 中的依赖关系
- android - 导航抽屉菜单不适用于proguard
- android - 如何设置 AlarmManager 准时触发 - Android Studio
- reactjs - onChange 没有显示数据,但它正在正确调用它
- python - 基于类的视图:CreateView success_url 不起作用