【问题标题】:Python: Shuffle and put back into initial order elements of an numpy arrayPython:随机播放并放回numpy数组的初始顺序元素
【发布时间】:2019-05-08 15:53:07
【问题描述】:

我有一个数组,我必须修改一些值。为此,我必须更改数组元素的顺序,在更改其值之后,我想将值放回初始顺序。但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)))] 

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

【问题讨论】:

    标签: arrays python-3.x numpy sorting


    【解决方案1】:

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

    解决办法是:

    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_)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多