gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:55:45 26 4
gpt4 key购买 nike

我有一个 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 应该包含 arr.shape[0] 介于 0 和 arr.shape[0] - 1 之间的唯一元素(两者都是包括)

我怎样才能使用 Numpy 高效地做到这一点(可能不需要使用任何显式循环)?

最佳答案

这是一个基于 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])

关于python - 根据范围替换numpy数组中的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55852379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com