Home > other >  From row to column vector for a specific condition in Python
From row to column vector for a specific condition in Python

Time:05-04

The code selects the positive values in the matrix and gives the corresponding indices. However, I would like the output of positive values in a column vector instead of a row. The current and desired outputs are attached.

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

The current output is

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

The desired output is

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

CodePudding user response:

IIUC, you can add an extra dimension when slicing your array:

values = Flux[Flux>=0,None]

output:

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

CodePudding user response:

You can use this:

values = [[x] for x in values]

and make it a numpy array like this:

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