基于0和非0的向量创建0和1的矩阵

时间:2017-06-14 07:54:02

标签: python

给出一个向量v=[0, 0, 0, 0, 2, 0, 0, 0, 2.5, 0, 0, 0]

我想创建一个num_rows = np.count_nonzero(v)num_cols = len(v)为0和1的矩阵,如下面的输出。我不清楚如何生成这样的矩阵。

输出:

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

2 个答案:

答案 0 :(得分:3)

试试这个:

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

答案 1 :(得分:1)

您可以考虑以下代码,它使用count_nonzero函数:

import numpy as np
v=[0, 0, 0, 0, 2, 0, 0, 0, 2.5, 0, 0, 0]
m = np.zeros((np.count_nonzero(v), len(v)))  # create a nxm matrix of zeros where n = #nonzero elements & m = size of vector
nonzero_indexes = np.nonzero(v) # find all nonzero elements - returns the positions
for row_index, col_index in enumerate(nonzero_indexes[0]): # iterate trough positions and update values.
    m[row_index, col_index] = 1
print(m)