Eric
Eric

Reputation: 847

Flatten a matrix into an array containing the index positions of the values

Given a numpy matrix, my_matrix.

import numpy as np

my_matrix = np.array([[1.2,2.3,None],[4.5,3.4,9.3]])

How can you efficiently flatten it into the following array containing the index positions of my_matrix?

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

Upvotes: 1

Views: 651

Answers (3)

Samufi
Samufi

Reputation: 2710

You can create such a list easily with pure python:

from itertools import product
list(product(range(my_matrix.shape[0]), range(my_matrix.shape[1])))

Result is

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]

If you are not using the explicit list but only want to iterate over the indices, leave the list(...) away. This will save memory and computation time, as the indices will be generated when they are used only.

However, if you want to use the result to index a numpy array, it may be more convenient to use np.ix_:

np.ix_(np.arange(my_matrix.shape[0]), np.arange(my_matrix.shape[1]))

Output is

(array([[0],
        [1]]), array([[0, 1, 2]]))

Upvotes: 0

kederrac
kederrac

Reputation: 17322

you can try:

rows, cols = my_matrix.shape
[[i, j] for i in range(rows) for j in range(cols)]

output:

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

Upvotes: 1

Nils Werner
Nils Werner

Reputation: 36805

You can use numpy.indices() and reshape the returned values a little bit

np.indices(my_matrix.shape).transpose(1, 2, 0).reshape(-1, 2)
# array([[0, 0],
#        [0, 1],
#        [0, 2],
#        [1, 0],
#        [1, 1],
#        [1, 2]])

Upvotes: 0

Related Questions