Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert 3D list to numpy array

I want to convert a 3D list to a numpy array.

When i am trying to do that using np.array(list) or np.asarray(list) it is giving 2D numpy array of shape (6,10).

How can I get numpy array of 3 dimensional(like shape should be (6,10,10). Can someone help me resolving this issue.

The list i am trying to convert is mentioned below

[[[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]]
[[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L] [4L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]]
[[0L, 1L, 2L] [0L, 1L, 2L] [0L, 1L, 2L] [0L, 1L, 2L, 3L]
[0L, 1L, 2L, 3L, 4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 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]
[0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L]]]
like image 612
sweety Avatar asked Oct 17 '22 01:10

sweety


2 Answers

If you build a 2D list and convert it to numpy with np.array() it will return a numpy array with 2 dimensions.

If you build a 3D list and convert it to numpy with np.array() it will return a numpy array with 3 dimensions.

Minimal working example:

my_list = [[[0,1,2],[0,1,2]],[[0,1,2],[0,1,2]]]
my_list

[[[0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2]]]

my_np_array = np.array(my_list)
my_np_array.shape

(2, 2, 3)

like image 95
Alber8295 Avatar answered Oct 21 '22 06:10

Alber8295


That's because this is not a 3D list. List has format [item,item]; 2D list would be [[],[]]. There are no inner level separators(',') in the file above. Load it into python and you get a 6,10 tuple back, the first valid entry after which no commas, so error out.

like image 35
HDunn Avatar answered Oct 21 '22 07:10

HDunn