我有一个关于重新排列numpy数组的问题,我有个numpy数组,它看起来像这样:
numpy_array = np.array([[ 1, 2, 3, 4, -10],
[ -4, 1, 1, 1, 1],
[ 2, -7, 1, 1, 3],
[ 1, 6, -12, 2, 3],
[ 0, 3, 1, -4, 0]])
我想重新排列这个数组:每行上的负值都会在对角线位置,也就是说,用对角线位置上的元素交换负元素,所以我在最后得到一个新的数组,如下所示:
numpy_array_new = np.array([[-10, 2, 3, 4, 1],
[ 1, -4, 1, 1, 1],
[ 2, 1, -7, 1, 3],
[ 1, 6, 2, -12, 3],
[ 0, 3, 1, 0, -4]])
我的想法是使用
np.fill_diagonal(numpy_array, 0)
当然,用负元素填充对角线,不是用0,而是每行都用负元素,有人知道吗?感谢您帮助
我假设一行中只有一个负值。
下面的代码返回所需的矩阵,不带任何for循环。
# Find negative elements and their index in a row
negative_indices =np.where(arr < 0)
negative_elements = arr[negative_indices]
diagonal_elements = arr.diagonal()
# Change negative elements with current diagonal values
arr[negative_indices] = diagonal_elements
# Fill diagonal with the negative elements
np.fill_diagonal(arr, negative_elements)
print(arr)
这是另一种基于交换特定索引项的方法:
idx_of_negatives = np.where(numpy_array < 0)
# it's a tuple ([0, 1, 2, 3, 4], [4, 0, 1, 2, 3])
idx_of_diagonal = (np.arange(len(numpy_array)), np.arange(len(numpy_array)))
# it's a tuple ([0, 1, 2, 3, 4], [0, 1, 2, 3, 4])
numpy_array[idx_of_negatives], numpy_array[idx_of_diagonal] =
numpy_array[idx_of_diagonal], numpy_array[idx_of_negatives]