Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a 2D array into a tuple in python 3?

type conversion

I have a numpy array of dimensions 667000 * 3 and I want to convert it to a 667000*3 tuple.

In smaller dimensions it would be like converting arr to t, where:

arr= [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

t= ((1,2,3),(4,5,6),(7,8,9),(10,11,12))

I have tried :

t = tuple((map(tuple, sub)) for sub in arr)   

but didn't work.

Can you help me how can I do that in python 3?

like image 511
Farzaneh Entezari Avatar asked Jan 28 '23 08:01

Farzaneh Entezari


2 Answers

You do not need to iterate over the sub, just first wrap every sublist in a tuple, and then wrap that result in a tuple, like:

tuple(map(tuple, arr))

For example:

>>> arr = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
>>> tuple(map(tuple, arr))
((1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12))

Here map will thus produce an generator that for each sublist (like [1, 2, 3]) will convert it to a tuple (like (1, 2, 3)). The outer tuple(..) constructor than wraps the elements of this generator in a tuple.

Based on an experiment, converting a 667000×3 matrix is feasible. When I run this for an np.arange(667000*3) and np.random.rand(667000, 3) it requires 0.512 seconds:

>>> arr = np.random.rand(667000,3)
>>> timeit.timeit(lambda: tuple(map(tuple, arr)), number=10)
5.120870679005748
>>> arr = np.arange(667000*3).reshape(-1, 3)
>>> timeit.timeit(lambda: tuple(map(tuple, arr)), number=10)
5.109966446005274
like image 134
Willem Van Onsem Avatar answered Feb 12 '23 00:02

Willem Van Onsem


A simple iterative solution to your problem would be to use a generator expression:

tuple(tuple(i) for i in arr)
# ((1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12))
like image 26
sacuL Avatar answered Feb 12 '23 02:02

sacuL