【发布时间】: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