python - finding all the indices of an array occuring in other arrays in python
问题描述
I have a numpy array and want to search for the indices where the search array exists in two other arrays:
searched=np.array([[1., 2.], [-3., 1.]])
I want to search for first half of searched
array in main_arr1
and second half in main_arr2
(in reality searched
array is much more longer but I will split it into two ones: first half and second half):
main_arr1=np.array([[1., 5.], [8., 3.], [-3., 8.], [2., 4.]])
main_arr2=np.array([[1., 7.], [-3., 1.], [4., 7.], [2., 4.]])
Then, I tried:
match1=np.where((main_arr1==searched[:int (len(searched)/2)][:,None]).any(-1))[1]
match2=np.where((main_arr2==searched[int (len(searched)/2):][:,None]).any(-1))[1]
to get:
match1=np.array([0., 3.])
match2=np.array([0., 1.])
But my code is only giving me:
match1=np.array([0.])
match1=np.array([1.])
I do not know why it is ignoring other indices. I do appreciate if anyone help me to solve this problem.
解决方案
一种解决方案可能是使用np.isin
searched=np.array([[1., 2.], [-3., 1.]])
main_arr1=np.array([[1., 5.], [8., 3.], [-3., 8.], [2., 4.]])
main_arr2=np.array([[1., 7.], [-3., 1.], [4., 7.], [2., 4.]])
match1 = np.where(np.isin(main_arr1,searched[:len(searched)//2]).any(-1))[0]
match2 = np.where(np.isin(main_arr2,searched[len(searched)//2:]).any(-1))[0]
输出:
>>> match1
array([0, 3])
>>> match2
array([0, 1])
推荐阅读
- c++ - Asio 如何包含基于 BSD 套接字 API 的低级套接字接口?
- amazon-web-services - BitBucket 管道 YAML 语法问题
- oracle - 调用函数时出现“文字与格式不匹配”错误
- go - 如何在亚马逊 ec2 上部署 Go 程序而不在 ec2 上编译?
- azure - Azure 门户中服务特权的物理位置?
- python - 为什么这个python版本的快速排序有运行时错误
- python - Tensorflow:经过 50 个 epoch 训练后,resnet-56 的学习率达到饱和,但测试准确度仍然不理想
- python - 我已经安装了 Python 3.7.10,但 macOS 在运行“python --version”时不断报告 2.7.10
- php - 调用构造函数参数闭包函数时未定义的函数
- mysql - Sequelize Migration 服务器连接两个数据库