简体   繁体   中英

Creating a array of 1s and 0s using another array

So I have two arrays (row and column) row = [0, 1, 0, 2, 0, 1, 3, 1, 3, 1, 2, 4] and column = [0, 0, 1, 1, 2, 2, 2, 3, 3, 0, 1, 4]

I want to use the rows and columns arrays to insert the value "1" into another 2D array (vectors)

vectors = 
[[0. 0. 0. 0. 0.],
[0. 0. 0. 0. 0.],
[0. 0. 0. 0. 0.],
[0. 0. 0. 0. 0.],
[0. 0. 0. 0. 0.]]

so my desired output is:

vectors = 
[[1. 1. 1. 0. 0.],
[1. 0. 1. 1. 0.],
[0. 1. 0. 0. 0.],
[0. 0. 1. 1. 0.],
[0. 0. 0. 0. 1.]]

Sorry if my explanation is bad it's my first time using python and Stackoverflow.

I think you could try this:

for r, c in zip(row, column):
    vectors[r][c] = 1

Just use the row and column vector as indices:

>>> vectors[row, column] = 1
>>> vectors
array([[1., 1., 1., 0., 0.],
       [1., 0., 1., 1., 0.],
       [0., 1., 0., 0., 0.],
       [0., 0., 1., 1., 0.],
       [0., 0., 0., 0., 1.]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM