求Numpy阵列中非均匀元素的指数

2024-10-01 00:19:32 发布

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

我发现了其他方法,比如this,可以从数组中删除重复的元素。我的要求稍有不同。如果我先说:

array([[1, 2, 3],
       [2, 3, 4],
       [1, 2, 3],
       [3, 2, 1],
       [3, 4, 5]])

最后我想说:

^{pr2}$

这就是我最终想要的,但还有一个额外的要求。我还想存储一个要丢弃或保留的索引数组(lanumpy.take)。在

我使用的是Numpy 1.8.1


Tags: 方法numpy元素数组thisarraytakepr2
3条回答

如果要删除重复版本中存在的元素的所有实例,可以遍历数组,找到多个版本中存在的元素的索引,最后删除这些:

# The array to check:
array = numpy.array([[1, 2, 3],
        [2, 3, 4],
        [1, 2, 3],
        [3, 2, 1],
        [3, 4, 5]])

# List that contains the indices of duplicates (which should be deleted)
deleteIndices = []

for i in range(0,len(array)): # Loop through entire array
    indices = range(0,len(array)) # All indices in array
    del indices[i] # All indices in array, except the i'th element currently being checked

for j in indexes: # Loop through every other element in array, except the i'th element, currently being checked
    if(array[i] == array[j]).all(): # Check if element being checked is equal to the j'th element
        deleteIndices.append(j) # If i'th and j'th element are equal, j is appended to deleteIndices[]

# Sort deleteIndices in ascending order:
deleteIndices.sort()

# Delete duplicates
array = numpy.delete(array,deleteIndices,axis=0)

该输出:

^{pr2}$

这样一来,您既可以删除重复项,又可以获得一个要丢弃的索引列表。在

我们希望找到数组中没有重复的行,同时保持顺序。在

我使用这个solutiona的每一行组合成一个元素,这样我们就可以使用np.unique(,return_index=True, return_inverse= True)来找到唯一的行。然后,我修改了这个function,使用索引和反转输出唯一行的计数。从那里,我可以选择具有counts == 1的所有唯一行。在

a = np.array([[1, 2, 3],
       [2, 3, 4],
       [1, 2, 3],
       [3, 2, 1],
       [3, 4, 5]])

#use a flexible data type, np.void, to combine the columns of `a`
#size of np.void is the number of bytes for an element in `a` multiplied by number of columns
b = a.view(np.dtype((np.void, a.dtype.itemsize * a.shape[1])))
_, index, inv = np.unique(b, return_index = True, return_inverse = True)

def return_counts(index, inv):
    count = np.zeros(len(index), np.int)
    np.add.at(count, inv, 1)
    return count

counts = return_counts(index, inv)

#if you want the indices to discard replace with: counts[i] > 1
index_keep = [i for i, j in enumerate(index) if counts[i] == 1]

>>>a[index_keep]
array([[2, 3, 4],
   [3, 2, 1],
   [3, 4, 5]])

#if you don't need the indices and just want the array returned while preserving the order
a_unique = np.vstack(a[idx] for i, idx in enumerate(index) if counts[i] == 1])
>>>a_unique
array([[2, 3, 4],
   [3, 2, 1],
   [3, 4, 5]])

为了np.版本>;=1.9

^{pr2}$

numpy_indexed包(免责声明:我是其作者)可用于以矢量化方式解决此类问题:

index = npi.as_index(arr)
keep = index.count == 1
discard = np.invert(keep)
print(index.unique[keep])

相关问题 更多 >