A1122 A1122 -4 years ago 46
Python Question

Create a matrix of 0s and 1s based on a vector of 0s and non-0s

Given a vector

v=[0, 0, 0, 0, 2, 0, 0, 0, 2.5, 0, 0, 0]


I want to create a matrix with
num_rows = np.count_nonzero(v)
and
num_cols = len(v)
of 0s and 1s like the output below. I'm not clear how to generate such a matrix.

output:

[[ 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]]

Answer Source

Try this:

m = np.zeros((np.count_nonzero(a), len(a)))
row_index = 0
for i in range(len(a)):
    if a[i] != 0:
        m[row_index][i] = 1
         row_index += 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download