Alejandro Sazo - 1 year ago 67

Python Question

I have a NxM numpy array filled with zeros and a 1D numpy array of size N with random integers between 0 to M-1. As you can see the dimension of the array matches the number of rows in the matrix. Each element in the integer array means that at that given position in its corresponding row must be set to 1. For example:

`# The matrix to be modified`

a = np.zeros((2,10))

# Indices array of size N

indices = np.array([1,4])

# Indexing, the result must be

a = a[at indices per row]

print a

[[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],

[0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]

I tried using the indexing

`a[:,indices]`

Answer Source

Use `np.arange(N)`

in order to address the rows and indices for columns:

```
>>> a[np.arange(2),indices] = 1
>>> a
array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.]])
```

Or:

```
>>> a[np.where(indices)+(indices,)] = 1
>>> a
array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.]])
```