首页 > 解决方案 > Python:随机播放并放回numpy数组的初始顺序元素

问题描述

我有一个必须修改一些值的数组。为此,我必须更改数组元素的顺序,在更改其值之后,我想将值放回初始顺序。但2小时后,我真的不知道怎么做。

更改顺序时,我需要将它们从绝对值的最大元素到最小元素进行排序。然后,我需要将元素的总和设为 = 到 1,因此我修改了元素,但随后无法重新排序数组。

这是我的代码:

output = np.random.uniform(-1, 1, (4, 1)).ravel()

sorted_weigths = np.sort(abs(output))[::-1]
sorted_indices = np.argsort(sorted_weigths)[::-1] 
signs = [i < 0 for i in output]  

if np.sum(abs(sorted_weigths)) > 1:
    alloc = 1
    for i in range(output.shape[0]):
        if alloc > abs(sorted_weigths[i]):
            sorted_weigths[i] = sorted_weigths[i]
            alloc = alloc - abs(sorted_weigths[i])
        elif alloc > 0:
            sorted_weigths[i] = alloc
            alloc = alloc - alloc
        else:
            sorted_weigths[i] = 0
else:
    pass

sorted_weigths[sorted_indices]

for i in range(len(signs)):
    if signs[i] == True:
        sorted_weigths[i] = -sorted_weigths[i]
    else:
        pass

我知道

output = np.random.uniform(-1, 1, (4, 1)).ravel()
sorted_weigths = np.sort(abs(output))
sorted_indices = np.argsort(sorted_weigths)
output[np.argsort(np.sort(abs(output)))] 

这是诀窍,但修改输出的值不起作用。因此,任何帮助或提示将不胜感激。非常感谢

标签: arrayspython-3.xnumpysorting

解决方案


解决方案实际上是根据原始输出的位置重新排序转换后的数组的位置,而不是通过跟踪打乱的索引。

解决方案是:

output = np.random.uniform(-1, 1, (4, 1)).ravel()

sorted_weigths = np.sort(abs(output))[::-1]
sorted_indices = np.argsort(abs(output))[::-1] 
signs = [i < 0 for i in output]  

if np.sum(abs(sorted_weigths)) > 1:
    alloc = 1
    for i in range(output.shape[0]):
        if alloc > abs(sorted_weigths[i]):
            sorted_weigths[i] = sorted_weigths[i]
            alloc = alloc - abs(sorted_weigths[i])
        elif alloc > 0:
            sorted_weigths[i] = alloc
            alloc = alloc - alloc
        else:
            sorted_weigths[i] = 0
else:
    pass

sorted_weigths_ = copy.deepcopy(sorted_weigths)
for i in range(sorted_indices.shape[0]):
    sorted_weigths_[sorted_indices[i]] = sorted_weigths[i]

for i in range(len(signs)):
    if signs[i] == True:
        sorted_weigths_[i] = -sorted_weigths_[i]
    else:
        pass

print(output)
print(sorted_weigths_)

推荐阅读