Wiz123
Wiz123

Reputation: 920

From row to column vector for a specific condition in Python

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

Upvotes: 1

Views: 56

Answers (2)

Rémi Baudoux
Rémi Baudoux

Reputation: 559

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

Upvotes: 1

mozway
mozway

Reputation: 261675

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

values = Flux[Flux>=0,None]

output:

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

Upvotes: 1

Related Questions