Find indices of rows of numpy 2d array in another 2D array(在另一个2D数组中查找NumPy 2D数组的行的索引)
本文介绍了在另一个2D数组中查找NumPy 2D数组的行的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是《麻木》的新手。 我有2个2维阵列。我想在arr1中找到arr2的索引。请给我提建议。
arr1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[4, 5, 6],
[1, 2, 3]]
arr2 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
desired_output = [0, 1, 2, 1, 0]
推荐答案
实现此目的的一种方法。
如果在中未找到arr1的任何行,则为简单起见,pos中的位置的值将为-1。
这会大量使用NumPybroadcasting和indexing。请随时要求进一步澄清。
原始示例:
import numpy as np
arr1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[4, 5, 6],
[1, 2, 3]])
arr2 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
inds = arr1 == arr2[:, None]
row_sums = inds.sum(axis = 2)
i, j = np.where(row_sums == 3) # Check which rows match in all 3 columns
pos = np.ones(arr1.shape[0], dtype = 'int64') * -1
pos[j] = i
pos
array([0, 1, 2, 1, 0])
示例2:
import numpy as np
arr1 = np.array([[1, 2, 4],
[4, 5, 6],
[7, 8, 9],
[4, 1, 6],
[1, 2, 3]])
arr2 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
inds = arr1 == arr2[:, None]
row_sums = inds.sum(axis = 2)
i, j = np.where(row_sums == 3)
pos = np.ones(arr1.shape[0], dtype = 'int64') * -1
pos[j] = i
pos
array([-1, 1, 2, -1, 0])
如果您有更多列数,只需将第i, j = np.where(row_sums == 3)行更改为i, j = np.where(row_sums == arr1.shape[1])。
这篇关于在另一个2D数组中查找NumPy 2D数组的行的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:在另一个2D数组中查找NumPy 2D数组的行的索引
基础教程推荐
猜你喜欢
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
