Aman
Aman

Reputation: 43

Converting list of tuples into numpy array and reshaping it?

I have three lists.

a = [1, 2, 3, 4, 5]  
b = [6, 7, 8, 9, 10]  
c = [11, 12 , 13, 14, 15]  

I combine them and make one list of tuples using list comprehension

combine_list = [(a1, b1, c1) for a1 in a for b1 in b for c1 in c]

This combine list has 5*5*5 = 125 elements.

Now I want to convert this combine_list into a numpy array with shape (5, 5, 5). So, I use the following code:

import numpy as np
combine_array = np.asarray(combine_list).reshape(5, 5, 5)

This gives me an error:

ValueError: total size of new array must be unchanged

But, when I try to reshape list of single 125 numbers (no tuple elements) to a numpy array, no such error occurs.

Any help on how to reshape list of tuples to a numpy array ?

Upvotes: 4

Views: 6080

Answers (2)

Jethro Cao
Jethro Cao

Reputation: 1050

Not sure if this is what you want, but you can use multi-dimensional list comprehension.

combine_list = [[[ (i, j, k) for k in c] for j in b] for i in a]
combine_array = np.asarray(combine_list)

Upvotes: 2

AChampion
AChampion

Reputation: 30258

If you really need the 3 ints in a 5x5x5 then you need a dtype of 3 ints. Using itertools.product to combine the lists:

>>> import itertools
>>> np.array(list(itertools.product(a,b,c)), dtype='int8,int8,int8').reshape(5,5,5)

Alternatively, just include the 3 elements in the reshape:

>>> np.array(list(itertools.product(a,b,c))).reshape(5,5,5,3)

Upvotes: 1

Related Questions