How can I convert numpy ndarray to a list of tuples efficiently?

# initial declaration
>>> a = np.array([[[ 0.01, 0.02 ]], [[ 0.03, 0.04 ]]])
>>> a
array([[[0.01, 0.02]],
       [[0.03, 0.04]]])

# check the shape
>>> a.shape
(2L, 1L, 2L)

# use resize() to change the shape (remove the 1L middle layer)
>>> a.resize((2, 2))
>>> a
array([[0.01, 0.02],
       [0.03, 0.04]])

# faster than a list comprehension (for large arrays)
# because numpy's backend is written in C

# if you need a vanilla Python list of tuples:
>>> list(map(tuple, a))
[(0.01, 0.02), (0.03, 0.04)]

# alternative one-liner:
>>> list(map(tuple, a.reshape((2, 2))))
...

You can use list comprehension, they are faster than for loops

a = np.array([[[ 0.01, 0.02 ]], [[ 0.03, 0.04 ]]])
print([(i[0][0], i[0][1]) for i in a])  # [(0.01, 0.02), (0.03, 0.04)]

alternatively:

print([tuple(l[0]) for l in a])  # [(0.01, 0.02), (0.03, 0.04)]

Tags:

Python

Numpy