【问题标题】:Get the indexes of a numpy array inside another numpy array [duplicate]获取另一个numpy数组中的numpy数组的索引[重复]
【发布时间】:2019-06-20 08:52:13
【问题描述】:

我正在尝试在另一个 numpy 数组中获取 numpy 数组的索引,例如,我有

 y = array([1, 2, 3, 4, 5, 8])
 x = np.array([3, 1, 8]) 

x 包含在 y 中,所以我想得到的是 y 数组上 x 数组的索引idx,顺序相同,所以这里是idx = array([2, 0, 5]),这样我们就有了@987654324 @产生True, 我尝试使用np.argwhere(np.in1d(y,x)),但显然我没有得到相同的顺序,我知道我总是可以使用列表理解idx = [ list(y).index(el) for el in x],但我更喜欢使用numpy。 有什么想法吗?

【问题讨论】:

    标签: python numpy numpy-ndarray


    【解决方案1】:

    来自Is there a NumPy function to return the first index of something in an array?

    >>> t = array([1, 1, 1, 2, 2, 3, 8, 3, 8, 8])
    >>> nonzero(t == 8)
    (array([6, 8, 9]),)
    >>> nonzero(t == 8)[0][0]
    6
    

    所以适应你的情况:

    lst=[]
    for item in x:
        lst.append( list(nonzero(y == item)) )
    

    【讨论】:

    • 是的,你是对的,但我更愿意避免 for 循环,因为它会减慢进程
    • 你可能不得不在某个地方使用一个循环,你可以通过理解将它压缩成一行
    猜你喜欢
    • 2018-10-25
    • 2011-07-27
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多