Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a different index for each row in a numpy array?

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] but this sets the same indices for each row, and this finally sets all the rows with ones. How can I set the given index to 1 per row?

like image 771
Alejandro Sazo Avatar asked Sep 10 '16 22:09

Alejandro Sazo


People also ask

How do you access different rows of a multidimensional NumPy array?

In NumPy , it is very easy to access any rows of a multidimensional array. All we need to do is Slicing the array according to the given conditions. Whenever we need to perform analysis, slicing plays an important role.

How do you change the index of an array in Python?

Try using enumerate , and use the enumerated index to change the element.

What is NumPy fancy indexing?

Fancy indexing is conceptually simple: it means passing an array of indices to access multiple array elements at once. For example, consider the following array: import numpy as np rand = np. random. RandomState(42) x = rand.


2 Answers

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.]])
like image 165
Mazdak Avatar answered Sep 27 '22 22:09

Mazdak


You should also check the np.eye() function which does exactly what you want. It basically creates 2D arrays filled with zero and diagonal ones.

>>> np.eye(a.shape[1])[indices]
array([[0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 1., 0., 0., 0., 0., 0.]])
like image 37
Ersel Er Avatar answered Sep 27 '22 22:09

Ersel Er