Not sure if I understood the question correctly, but does this work for you?
import numpy as np
A = [[1,2,3],[4,5,6],[7,8,9]]
A = np.array(A)
If A is a list of numpy array, how about this:
Ah = np.vstack(A)
Av = np.hstack(A)
Answer from YS-L on Stack OverflowNot sure if I understood the question correctly, but does this work for you?
import numpy as np
A = [[1,2,3],[4,5,6],[7,8,9]]
A = np.array(A)
If A is a list of numpy array, how about this:
Ah = np.vstack(A)
Av = np.hstack(A)
If I understood correctly what you're asking, you have a case where numpy did not convert array of arrays into 2d array. This can happen when your arrays are not of the same size. Example:
Automatic conversion to 2d array:
import numpy as np
a = np.array([np.array([1,2,3]),np.array([2,3,4]),np.array([6,7,8])])
print a
Output:
>>>[[1 2 3]
[2 3 4]
[6 7 8]]
No automatic conversion (look for the change in the second subarray):
import numpy as np
b = np.array([np.array([1,2,3]),np.array([2,3,4,5]),np.array([6,7,8])])
print b
Output:
>>>[array([1, 2, 3]) array([2, 3, 4, 5]) array([6, 7, 8])]
I found a couple of ways of converting an array of arrays to 2d array. In any case you need to get rid of subarrays which have different size. So you will need a mask to select only "good" subarrays. Then you can use this mask with list comprehensions to recreate array, like this:
import numpy as np
a = np.array([np.array([1,2,3]),np.array([2,3,4,5]),np.array([6,7,8])])
mask = np.array([True, False, True])
c = np.array([element for (i,element) in enumerate(a) if mask[i]])
print a
print c
Output:
>>>>[array([1, 2, 3]) array([2, 3, 4, 5]) array([6, 7, 8])]
>>>>[[1 2 3]
[6 7 8]]
Or you can delete "bad" subarrays and use vstack(), like this:
import numpy as np
a = np.array([np.array([1,2,3]),np.array([2,3,4,5]),np.array([6,7,8])])
mask = np.array([True, False, True])
d = np.delete(a,np.where(mask==False))
e = np.vstack(d)
print a
print e
Output:
>>>>[array([1, 2, 3]) array([2, 3, 4, 5]) array([6, 7, 8])]
>>>>[[1 2 3]
[6 7 8]]
I believe second method would be faster for large arrays, but I haven't tested the timing.
Videos
>>> import numpy as np
>>> np.array(data_list).reshape(-1, 2)
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
(The reshape method returns a new "view" on the array; it doesn't copy the data.)
def nest_list(list1,rows, columns):
result=[]
start = 0
end = columns
for i in range(rows):
result.append(list1[start:end])
start +=columns
end += columns
return result
for:
list1=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
nest_list(list1,4,4)
Output:
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]
Just pass the list to np.array:
a = np.array(a)
You can also take this opportunity to set the dtype if the default is not what you desire.
a = np.array(a, dtype=...)
np.array() is even more powerful than what unutbu said above.
You also could use it to convert a list of np arrays to a higher dimention array, the following is a simple example:
aArray=np.array([1,1,1])
bArray=np.array([2,2,2])
aList=[aArray, bArray]
xArray=np.array(aList)
xArray's shape is (2,3), it's a standard np array. This operation avoids a loop programming.
I have a list:
data=[1,2,3,4,5,6,7,...]
and I want to transform it into a 2-dimensional array, with 5 columns and 10 rows
How can I do it?
Hello, I have a simple question : For example, I have 3 lists a,b,c , and I want to join them into one big 2d array called d, how do I do it:
a= [1,2,3]
b= [4,5,6]
c= [7,8,9]
result wanted :
d= [
[1,2,3],
[4,5,6],
[7,8,9]
]
thank you !!!
If your lists are NOT of the same length (in each nested dimension) you CANT do a traditional conversion to a NumPy array because it's necessary for a NumPy array of 2D or above to have the same number of elements in its first dimension.
So you cant convert [[1,2],[3,4,5]] to a numpy array directly. Applying np.array will give you a 2 element numpy array where each element is a list object as - array([list([1, 2]), list([3, 4, 5])], dtype=object). I believe this is the issue you are facing.
You cant create a 2D matrix for example that looks like -
[[1,2,3,?],
[4,5,6,7]]
What you may need to do is pad the elements of each list of lists of lists to a fixed length (equal lengths for each dimension) before converting to a NumPy array.
I would recommend iterating over each of the lists of lists of lists as done in the code I have written below to flatten your data, then transforming it the way you want.
If your lists are of the same length, then should not be a problem with numpy version 1.18.5 or above.
a = [[[1,2],[3,4]],[[5,6],[7,8]]]
np.array(a)
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
However, if you are unable to still work with the list of list of lists, then you may need to iterate over each element first to flatten the list and then change it into a numpy array with the required shape as below -
a = [[[1,2],[3,4]],[[5,6],[7,8]]]
flat_a = [item for sublist in a for subsublist in sublist for item in subsublist]
np.array(flat_a).reshape(2,2,2)
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
Try this:
>>> import numpy as np
>>> a = np.array([[[1,2],[3,4],[5,6]],[[7,8],[9,10],[11,12]]])
>>> a
array([[[ 1, 2],
[ 3, 4],
[ 5, 6]],
[[ 7, 8],
[ 9, 10],
[11, 12]]])
>>> a.reshape(4,-1)
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
>>> a.reshape(1,-1)
array([[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]])
Try something like that:
In [53]: l = [0,1,2,3]
In [54]: def to_matrix(l, n):
...: return [l[i:i+n] for i in xrange(0, len(l), n)]
In [55]: to_matrix(l,2)
Out[55]: [[0, 1], [2, 3]]
I think you should use numpy, which is purpose-built for working with matrices/arrays, rather than a list of lists. That would look like this:
>>> import numpy as np
>>> list_ = [0,1,2,3]
>>> a = np.array(list_).reshape(2,2)
>>> a
array([[0, 1],
[2, 3]])
>>> a.shape
(2, 2)
Avoid calling a variable list as it shadows the built-in name.
You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this "list comprehension".
# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5
Matrix = [[0 for x in range(w)] for y in range(h)]
#You can now add items to the list:
Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range...
Matrix[0][6] = 3 # valid
Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".
print Matrix[0][0] # prints 1
x, y = 0, 6
print Matrix[x][y] # prints 3; be careful with indexing!
Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.
If you really want a matrix, you might be better off using numpy. Matrix operations in numpy most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:
>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):
numpy.arange(25).reshape((5, 5)) # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5)) # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5)) # pass a Python list and reshape
numpy.empty((5, 5)) # allocate, but don't initialize
numpy.ones((5, 5)) # initialize with ones
numpy provides a matrix type as well, but it is no longer recommended for any use, and may be removed from numpy in the future.