【问题标题】:How to find in a parent string list, the indexes corresponding to a child string list如何在父字符串列表中查找子字符串列表对应的索引
【发布时间】:2015-07-01 22:38:49
【问题描述】:

我正在编写一个从文本文件中读取数据的代码。我使用 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 数组中找到这些“项目”索引,而不进行 for 循环和 if 检查。

我想知道是否可以使用任何 numpy 方法来完成:我想使用 intercept1d 来查找常见项目,然后使用 searchsorted。但是,我不能对我的“产品”列表进行排序,因为我不想松开原始排序(例如,我会使用索引直接查找每个产品的库存)。

关于“pythonish”解决方案的任何建议?

【问题讨论】:

    标签: python arrays string numpy indexing


    【解决方案1】:

    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 更喜欢这个解决方案 - 根据查询顺序返回索引的能力似乎特别有用。
    【解决方案2】:

    您可以使用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])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-29
      • 2021-04-21
      • 2012-05-16
      • 2013-05-08
      • 1970-01-01
      • 2023-04-03
      • 2018-09-27
      相关资源
      最近更新 更多