Python中特定条件的从行到列向量



代码选择矩阵中的正值并给出相应的索引。然而,我希望输出的正值的列向量,而不是一行。电流和期望输出已附上。

import numpy as np
from numpy import nan
import math
Flux=np.array([[-1, 2, 0],[4,-7,8],[1,-9,3]])
values = Flux[Flux >= 0]
print("positive values =",[values])
indices = np.array(np.where(Flux >= 0)).T
print("indices =",[indices])

当前输出为

positive values = [array([2, 0, 4, 8, 1, 3])]
indices = [array([[0, 1],
[0, 2],
[1, 0],
[1, 2],
[2, 0],
[2, 2]], dtype=int64)]

期望的输出是

positive values = [array([[2], [0], [4], [8], [1], [3]])]
indices = [array([[0, 1],
[0, 2],
[1, 0],
[1, 2],
[2, 0],
[2, 2]], dtype=int64)]

如果是这样的话,您可以在切片数组时添加一个额外的维度:

values = Flux[Flux>=0,None]

输出:

array([[2],
[0],
[4],
[8],
[1],
[3]])

你可以这样做:

values = [[x] for x in values]

并将其设置为如下的numpy数组:

values = Flux[Flux >= 0]
values = np.array([[x] for x in values])
print("positive values =",[values])

最新更新