Del*_*ari 3 python arrays string indexing numpy
我正在编写一个从文本文件中读取数据的代码.我使用numpy loadtxt加载数据,它看起来像这样:
import numpy as np
Shop_Products = np.array(['Tomatos', 'Bread' , 'Tuna', 'Milk', 'Cheese'])
Shop_Inventory = np.array([12, 6, 10, 7, 8])
Run Code Online (Sandbox Code Playgroud)
我想检查一下我的产品:
Shop_Query = np.array(['Cheese', 'Bread']
Run Code Online (Sandbox Code Playgroud)
现在我想在Shop_Products数组中找到这些"items"indeces,而不进行for循环和检查.
我想知道是否可以使用任何numpy方法:我想使用intercept1d找到常见项目然后使用searchsorted.但是,我无法对"产品"列表进行排序,因为我不想放弃原始排序(例如,我会使用索引直接查找每个产品的库存).
关于"pythonish"解决方案的任何建议?
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])
Run Code Online (Sandbox Code Playgroud)
这可能比快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]),)
Run Code Online (Sandbox Code Playgroud)