zsoq
zsoq

Reputation: 57

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.

Upvotes: 1

Views: 99

Answers (2)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

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

Upvotes: 2

Mark Moretto
Mark Moretto

Reputation: 2348

I think you could try this:

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

Upvotes: 2

Related Questions