如何在父字符串列表中查找子字符串列表对应的索引

How to find in a parent string list, the indexes corresponding to a child string list

我正在编写一个从文本文件中读取数据的代码。我使用 numpy loadtxt 加载数据,它看起来像这样:

import numpy as np

Shop_Products  = np.array(['Tomatos', 'Bread' , 'Tuna', 'Milk', 'Cheese'])
Shop_Inventory = np.array([12, 6, 10, 7, 8])

我想查看我拥有的一些产品:

Shop_Query     = np.array(['Cheese', 'Bread']

现在我想在 Shop_Products 数组中找到这些 "items" 个索引,而无需执行 for 循环和 if 检查。

我想知道是否可以使用任何 numpy 方法来完成:我想到了使用 intercept1d to find the common items and then use searchsorted。但是,我无法对 "Products" 列表进行排序,因为我不想丢失原始排序(例如,我会使用索引直接查找每个产品的库存)。

对 "pythonish" 解决方案有什么建议吗?

您可以使用 in1d()nonzero() 来查找 Shop_Products 中项目的索引:

>>> np.in1d(Shop_Products, Shop_Query).nonzero()
(array([1, 4]),)

(in1d returns 一个布尔数组,指示某项是否在第二个列表中,nonzero returns True 值的索引。 )

要在Shop_Inventory中查找相应的值,使用这个结果来索引数组:

>>> i = np.in1d(Shop_Products, Shop_Query).nonzero()
>>> Shop_Inventory[i]
array([6, 8])

np.searchsorted 可以将排序排列作为可选参数:

>>> sorter = np.argsort(Shop_Products)
>>> sorter[np.searchsorted(Shop_Products, Shop_Query, sorter=sorter)]
array([4, 1])
>>> Shop_Inventory[sorter[np.searchsorted(Shop_Products, Shop_Query, sorter=sorter)]]
array([8, 6])

这可能比np.in1d快,后者也需要对数组进行排序。它还 returns 值的顺序与它们在 Shop_Query 中出现的顺序相同,而 np.1d 将 return 值按照它们在 Shop_Products 中出现的顺序排列,无论查询中的顺序如何:

>>> np.in1d(Shop_Products, ['Cheese', 'Bread']).nonzero()
(array([1, 4]),)
>>> np.in1d(Shop_Products, ['Bread', 'Cheese']).nonzero()
(array([1, 4]),)