【问题标题】:Identifying column indices that a subsetted np array came from in larger np array识别子集 np 数组来自较大 np 数组的列索引
【发布时间】:2018-06-01 11:55:30
【问题描述】:

我有一个“大”的 numpy 数组,如下所示:

from numpy import array
large = array([[-0.047391  , -0.10926778, -0.00899118,  0.07461428, -0.07667476,
         0.06961918,  0.09440736,  0.01648382, -0.04102225, -0.05038805,
        -0.00930337,  0.3667651 , -0.02803499,  0.02597451, -0.1218804 ,
         0.00561949],
       [-0.00253788, -0.08670117, -0.00466262,  0.07330351, -0.06403728,
         0.00301005,  0.12807456,  0.01198117, -0.04290793, -0.06138136,
        -0.01369276,  0.37094407, -0.03747804,  0.04444246, -0.01162705,
         0.00554793]])

还有一个从large 子集的“小”数组。

small = array([[-0.10926778, -0.07667476,  0.09440736],
       [-0.08670117, -0.06403728,  0.12807456]])

在没有任何其他信息的情况下,我们如何识别large 中生成small 数组的列索引?

在这种情况下,答案是 1、4、6(在 python 中从 0 开始)。

确定这一点的通用方法是什么?

【问题讨论】:

  • np.where(np.isin(...))。查看[numpy] isin上的相关问题,这可能是重复的。

标签: python arrays numpy slice


【解决方案1】:

类似这样的东西(不确定如何将结果从 2D 压缩到 1D?):

>>> np.isin(large,small)
array([[False,  True, False, False,  True, False,  True, False, False,
        False, False, False, False, False, False, False],
       [False,  True, False, False,  True, False,  True, False, False,
        False, False, False, False, False, False, False]], dtype=bool)

>>> np.where(np.isin(large,small)) # tuple of arrays
(array([0, 0, 0, 1, 1, 1]), array([1, 4, 6, 1, 4, 6]))

# And generalizing, if you really want that as 2x2x3 array of indices:
idxs = array(np.where(np.isin(large,small)))
idxs.reshape( (2,) + small.shape )

array([[[0, 0, 0],
        [1, 1, 1]],

       [[1, 4, 6],
        [1, 4, 6]]])

【讨论】:

    猜你喜欢
    • 2018-08-28
    • 2011-11-04
    • 2022-07-08
    • 2020-11-27
    • 2023-02-10
    • 2022-06-11
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    相关资源
    最近更新 更多