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.
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.
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.
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.)
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.
# 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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With