在较大的np数组中标识子集np数组来自的列索引

2024-04-25 22:28:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个“大”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开始)

什么是确定这一点的普遍方法


Tags: 方法答案fromimportnumpy信息数组array
1条回答
网友
1楼 · 发布于 2024-04-25 22:28:52

类似这样的内容(不确定要如何将结果从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]]])

相关问题 更多 >