python - 迭代两个具有索引的 2D numpy 数组
问题描述
我有两个相同形状的 2D numpy 数组。有没有办法同时遍历它们,同时从两个表和它们的索引中获取一对元素?
例如,我有两个数组
before = np.array(
[[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]],
dtype=int
)
after = np.array(
[[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 1]],
dtype=int
)
我想zero
从before
表中获取已转换为表中one
的每个表的索引列表after
- 在这种情况下将是[(0, 2), (1, 4), (1, 7)]
。
numpy.ndenumerate
非常接近我想要实现的目标,但它一次只能遍历一个数组。
解决方案
您可以将这两个条件传递给np.logical_and
,然后用于np.argwhere
查找同时满足这两个条件的索引:
idx = np.argwhere(np.logical_and(before==0, after==1))
输出:
[[0 2]
[1 4]
[1 7]]
推荐阅读
- java - 来自 Fortify 扫描的 Delta 问题
- c - 如何在 Windows 上捕获原始键盘输入
- reactjs - 从客户端调用时,AWS GET 请求返回网络错误
- android - 从网络获取新数据后如何将 RecyclerView 滚动到顶部;我正在使用 ListAdapter、DiffUtil
- javascript - Jqxgrid 导出到 Excel 错误 - “q.toISOString 不是函数”
- c++ - C++ unique_ptr 对象访问
- javascript - 过滤数组返回空
- anaconda - 如何在 anaconda 中安装 snowflake.sqlalchemy?
- laravel - Laravel ErrorPlugin 需要升级
- python - 为什么我的 GUI 输入值在 Tkinter 中重复?