如何在一个父字符串列表中找到与子字符串列表对应的索引?

4

我正在编写一段代码,从文本文件中读取数据。我使用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']

现在我想在不使用for循环和if检查的情况下,在Shop_Products数组中找到这些“items”的索引。我想知道是否可以使用numpy方法之一来完成:我考虑使用intercept1d来查找公共项,然后使用searchsorted。但是,我不能对我的“Products”列表进行排序,因为我不想失去原始排序(例如,我将使用索引直接查找每个产品的库存)。有关“pythonish”解决方案的任何建议?
2个回答

9

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更快,后者还需要对数组进行排序。它的返回值与Shop_Query中出现的顺序相同,而np.1d将返回在Shop_Products中出现的顺序,不考虑查询中的顺序:

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

我喜欢这个解决方案,比起我的 in1d 更好 - 根据查询的顺序返回索引的能力特别有用。 - Alex Riley

3
你可以使用in1d()nonzero()函数来查找Shop_Products中的项目索引:
>>> np.in1d(Shop_Products, Shop_Query).nonzero()
(array([1, 4]),)

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

要查找 Shop_Inventory 中对应的值,请使用此结果来索引数组:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接