简体   繁体   中英

How to create a 2D array from a list of list in python?

I have a list of lists that looks something like this:

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

I want to create a 2 by 2 array with the first 2 elements at the top and the last two at the bottom, something like:

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

What I tried so far was reshape using:

np.array(arr).reshape(2,2)

However whenever I do that I get a ValueError: total size of new array must be unchanged What exactly am I missing or how can I get this to work?

Try using a list comprehension:

nparr = np.array([arr[i:i + 2] for i in range(0, len(arr), 2)]
print(nparr)

Output:

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

You could go for something like this, which reshapes the numpy array.

import numpy as np
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
out = np.reshape(sum([], arr), (-1, 3))
print(out)

Output:

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

I think what you want is not exactly possible like this but this could satisfy your needs:

arr2 = [arr[:2], arr[2:]]
np.array(arr2)

This returns something like this:

[[[ 1  2  3]
  [ 4  5  6]]

 [[ 7  8  9]
  [10 11 12]]]

Note that arr has a total of 12 elements. You can not arrange 12 elements in a 2,2 manner using reshape.

This is a possible solution for you

 np.array(arr).reshape(2, 6)

Output

array([[ 1,  2,  3,  4,  5,  6],
       [ 7,  8,  9, 10, 11, 12]])

There seems to be some confusion as to what you want:

In [93]: alist = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

Making an array from the list:

In [94]: np.array(alist)
Out[94]: 
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])
In [95]: _.shape
Out[95]: (4, 3)

That's a total of 12 elements. reshape has to match that:

In [96]: np.array(alist).reshape(2,2,3)
Out[96]: 
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]]])
In [97]: _.shape
Out[97]: (2, 2, 3)

The accepted answer does the same thing:

In [99]: np.array([alist[i:i + 2] for i in range(0, len(alist), 2)])
Out[99]: 
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]]])

In nested list form:

In [100]: [alist[i:i + 2] for i in range(0, len(alist), 2)]
Out[100]: [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]

When defining/displaying 2 and 3d arrays, the [] are more important than the line breaks and spacing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM