Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

Here's the numpy.ndarray I've got:

a=[[[ 0.01, 0.02 ]], [[ 0.03, 0.04 ]]]

and I want it to convert to

a = [(0.01, 0.02), (0.03, 0.04)]

Currently I just use the following for loop but I'm not sure whether it's efficient enough:

b = []
for point in a:
   b.append((point[0][0], point[0][1]))
print(b)

I've found somewhat a similar question but there're no tuples so a suggested ravel().tolist() approach didn't work for me here.

like image 642
Alex Avatar asked Mar 25 '19 11:03

Alex


People also ask

How do you turn Ndarray into a list?

To convert a one-dimensional NumPy array to a list use tolist() function of the ndarray, First, let's create a ndarray using array() function and then use tolist() function to convert it to a list. The array() function takes a Python list as an argument.

Is NumPy array more efficient than list?

NumPy Arrays are faster than Python Lists because of the following reasons: An array is a collection of homogeneous data-types that are stored in contiguous memory locations. On the other hand, a list in Python is a collection of heterogeneous data types stored in non-contiguous memory locations.

Are tuples faster than NumPy arrays?

If the code can be vectorized, then numpy will most likely be faster than Python tuples. (The only case I could imagine where it might not be, is if you had many very small tuples. In this case the overhead of forming the numpy arrays and one-time cost of importing numpy might drown-out the benefit of vectorization.)

How much faster is NumPy array than list?

As the array size increase, Numpy gets around 30 times faster than Python List. Because the Numpy array is densely packed in memory due to its homogeneous type, it also frees the memory faster.


2 Answers

# 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))))
...
like image 177
meowgoesthedog Avatar answered Sep 24 '22 02:09

meowgoesthedog


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)]
like image 39
rahul Avatar answered Sep 26 '22 02:09

rahul