python - 如何通过numpy中的指定数组获取索引
问题描述
我有以下数组。我想通过数组的搜索键提取索引。
np.array([[1,2],[2,2], [3,2], [2,2]])
的shep是(4, 2)
。所以搜索的结果[2, 2]
应该返回[1, 3]
哪个是 的索引[2, 2]
。np.argwhere
是一个强大的功能,但是,如何将其用于我的目的?
In [31]: d=np.array([[1,2],[2,2], [3,2], [2,2]])
In [32]: d
Out[32]:
array([[1, 2],
[2, 2],
[3, 2],
[2, 2]])
In [33]: np.where(d==np.array([2,2]))
Out[33]: (array([0, 1, 1, 2, 3, 3]), array([1, 0, 1, 1, 0, 1]))
In [34]: np.argwhere(d==np.array([2,2]))
Out[34]:
array([[0, 1],
[1, 0],
[1, 1],
[2, 1],
[3, 0],
[3, 1]])
解决方案
Use np.all(..., axis=1)
to reduce the boolean array over the second axis, then use np.where
:
np.where((d == [2, 2]).all(1))[0]
# array([1, 3])
推荐阅读
- wordpress - Wordpress REST API 无法发表评论
- delphi - TFDQuery 无法更新?
- react-native - React Native - 锁定设备屏幕上的原生音频播放器
- java - 如何选择正确的方式在 Java 中获取相关上下文?
- c++ - boost tcp 接受器的 cancel() 方法是否会取消在不同 io_context 上工作的套接字上的操作?
- visual-studio-code - 根据给定版本的 Visual Studio Code 检查是否存在更新的 URL 是什么
- python - 提取具有最频繁值的行
- java - 为什么保存方法需要使用已经存在的EntityManager?
- image - Rails Assets,可以在生产模式下预编译和非编译吗?
- python-3.x - 模块'pygame.locals'没有'QUIT' Python 3.8.2 Pygame