根据范围替换numpy数组中的重复元素

问题描述 投票:3回答:2

我有一个1d numpy数组arr如下:

arr = np.array([9, 7, 0, 4, 7, 4, 2, 2, 3, 7])

对于重复元素,我希望随机选择包含相同元素的任何一个索引,并将其替换为0arr.shape[0]之间缺失的值。

例如在给定的数组中,7存在于索引1,4和9中。因此,我希望随机选择1,4和9之间的索引,并通过随机选择一些像数字8这样的元素来设置其值,这在数组中是不存在的。最后,arr应该包含介于0和arr.shape[0](包括两者)之间的arr.shape[0] - 1独特元素

如何使用Numpy有效地执行此操作(可能不需要使用任何显式循环)?

python numpy random duplicates numpy-ndarray
2个回答
3
投票

这是一个基于np.isin的 -

def create_uniques(arr):
    # Get unique ones and the respective counts
    unq,c = np.unique(arr,return_counts=1)

    # Get mask of matches from the arr against the ones that have 
    # respective counts > 1, i.e. the ones with duplicates
    m = np.isin(arr,unq[c>1])

    # Get the ones that are absent in original array and shuffle it
    newvals = np.setdiff1d(np.arange(len(arr)),arr[~m])
    np.random.shuffle(newvals)

    # Assign the shuffled values into the duplicate places to get final o/p
    arr[m] = newvals
    return ar

样品运行 -

In [53]: arr = np.array([9, 7, 0, 4, 7, 4, 2, 2, 3, 7])

In [54]: create_uniques(arr)
Out[54]: array([9, 7, 0, 1, 6, 4, 8, 2, 3, 5])

In [55]: arr = np.array([9, 7, 0, 4, 7, 4, 2, 2, 3, 7])

In [56]: create_uniques(arr)
Out[56]: array([9, 4, 0, 5, 6, 2, 7, 1, 3, 8])

In [57]: arr = np.array([9, 7, 0, 4, 7, 4, 2, 2, 3, 7])

In [58]: create_uniques(arr)
Out[58]: array([9, 4, 0, 1, 7, 2, 6, 8, 3, 5])

2
投票

扩展Divakar的答案(我基本上没有python的经验,所以这可能是一个非常迂回和unpython的方式,但是):

import numpy as np
def create_uniques(arr):
    np.random.seed()
    indices = []
    for i, x in enumerate(arr):
        indices.append([arr[i], [j for j, y in enumerate(arr) if y == arr[i]]])
        indices[i].append(np.random.choice(indices[i][1]))
        indices[i][1].remove(indices[i][2])
    sidx = arr.argsort()
    b = arr[sidx]
    new_vals = np.setdiff1d(np.arange(len(arr)),arr)
    arr[sidx[1:][b[:-1] == b[1:]]] = new_vals
    for i,x in enumerate(arr):
        if x == indices[i][0] and i != indices[i][2]:
            arr[i] = arr[indices[i][2]]
            arr[indices[i][2]] = x
    return arr

样品:

arr = np.array([9, 7, 0, 4, 7, 4, 2, 2, 3, 7])
print(arr)
print(create_uniques(arr))
arr = np.array([9, 7, 0, 4, 7, 4, 2, 2, 3, 7])
print(create_uniques(arr))
arr = np.array([9, 7, 0, 4, 7, 4, 2, 2, 3, 7])
print(create_uniques(arr))
arr = np.array([9, 7, 0, 4, 7, 4, 2, 2, 3, 7])
print(create_uniques(arr))

输出:

[9 7 0 4 7 4 2 2 3 7]
[9 7 0 4 6 5 2 1 3 8]
[9 8 0 4 6 5 1 2 3 7]
[9 8 0 4 6 5 2 1 3 7]
[9 7 0 5 6 4 2 1 3 8]
© www.soinside.com 2019 - 2024. All rights reserved.