Since that middle dimension is size 1, just reshape or squeeze it.
x = np.array(alist)
x = np.squeeze(x) # or
x = x.reshape(45, 5785) # or
x = x[:,0,:]
You can remove the extra layer of nesting in the list, but this kind of reshaping is so much easier with arrays.
Answer from hpaulj on Stack OverflowSince that middle dimension is size 1, just reshape or squeeze it.
x = np.array(alist)
x = np.squeeze(x) # or
x = x.reshape(45, 5785) # or
x = x[:,0,:]
You can remove the extra layer of nesting in the list, but this kind of reshaping is so much easier with arrays.
From x[0], you have an extra level of list wrapped around. Removing it by indexing should get you there:
x = np.array([l[0] for l in x])
Here is a small example:
x = [[[1,2]], [[2,3]], [[4,5]]]
np.array(x).shape
# (3, 1, 2)
np.array([l[0] for l in x]).shape
# (3, 2)
np.array([l[0] for l in x])
# array([[1, 2],
# [2, 3],
# [4, 5]])
python - Converting list to numpy array - Stack Overflow
python - Converting List of Numpy Arrays to Numpy Matrix - Stack Overflow
Python - convert list of lists into matrix - Stack Overflow
python - how to convert 2d list to 2d numpy array? - Stack Overflow
If your list of lists contains lists with varying number of elements then the answer of Ignacio Vazquez-Abrams will not work. Instead there are at least 3 options:
1) Make an array of arrays:
x=[[1,2],[1,2,3],[1]]
y=numpy.array([numpy.array(xi) for xi in x])
type(y)
>>><type 'numpy.ndarray'>
type(y[0])
>>><type 'numpy.ndarray'>
2) Make an array of lists:
x=[[1,2],[1,2,3],[1]]
y=numpy.array(x)
type(y)
>>><type 'numpy.ndarray'>
type(y[0])
>>><type 'list'>
3) First make the lists equal in length:
x=[[1,2],[1,2,3],[1]]
length = max(map(len, x))
y=numpy.array([xi+[None]*(length-len(xi)) for xi in x])
y
>>>array([[1, 2, None],
>>> [1, 2, 3],
>>> [1, None, None]], dtype=object)
>>> numpy.array([[1, 2], [3, 4]])
array([[1, 2], [3, 4]])
If you have a list of lists, you only needed to use ...
import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)
per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.
If you're converting a list into an array, you'll need to make a new copy anyway, so
arr = np.array(my_list, dtype='float32')
also works.
One use case is when my_list is not actually a list but some other list-like object; in which case explicitly casting to list beforehand might be helpful.
arr = np.array(list(my_list), dtype='float32')
For example,
my_list = pd.Series([[1], [2], [3]]).values
np.array(my_list) # jagged array; not OK
np.array(list(my_list)) # OK
np.array(my_list.tolist()) # OK
my_list = {'a': [1], 'b': [2]}.values()
np.array(my_list) # jagged array; not OK
np.array(list(my_list)) # OK
To cast nested list into an array, the shapes of the sublists must match. If they don't maybe you want to concatenate the sublists along some axis. Try np.concatenate/np.r_/np.c_ etc. instead.
If they all have the same length, try this:
import numpy as np
list1 = [1,2,3]
list2 = [1,5,9]
list3 = [2,4,1]
Root_List = [list1, list2,list3]
np.array(Root_List)
A matrix is a list of list.
Best practice is to first define your root list, then append sublists you want:
Root_List = []
list1 = [1, 2, 3]
Root_List.append(list1)
list2 = [1, 5, 9]
Root_List.append(list2)
list3 = [2, 4, 1]
Root_List.append(list3)
As suggested by @Antonio Manrique, you can also convert it using numpy to benefit matrix calculation functions of this lib. This answer answer how to convert a python list of list to a numpy matrix.
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.
Do you mean this (a matrix as a list of lists):
In [1]: matrix = [[1,2,3]]
In [2]: matrix
Out[2]: [[1, 2, 3]]
In [3]: matrix.append([4,5,6])
In [4]: matrix
Out[4]: [[1, 2, 3], [4, 5, 6]]
This can be done very easily:
def list_to_matrix(lst):
return [lst]
Usage:
>>> lst = [1,2,3,4]
>>> lst = list_to_matrix(lst)
>>> lst
[[1,2,3,4]]
If we have cases where we might get things that are already in list-of-list form, we can add a little more robustness by doing this:
from collections import Iterable
def list_to_matrix(lst):
if lst:
return lst if all(isinstance(item, Iterable) and not isinstance(item, str) for item in lst) else [lst]
else:
# returns empty matrix if input list was empty
return [[]]
Note that this method is pretty fragile, but at least allows you to safely pass either a base list or a list of list form blindly and get back the correct thing.
Here is my code:
b = np.empty((0,2,2), dtype = float) a = np.empty((0,2), dtype=float) a = np.append(a,[(3,4)], axis=0) a = np.append(a,[(5,6)], axis=0) display(a) print (a[np.newaxis].shape) print (b.shape) b = np.append(b, a[np.newaxis], axis=0) display(b) a = np.empty((0,2), dtype=float) a = np.append(a,[(3.5,4)], axis=0) a = np.append(a,[(5.2,6)], axis=0) display(a) np.append(b, a[np.newaxis], axis=0)
A couple of things feel clumsy to me. The main thing is having to specify the size of most of the dimensions of the matrix and not just the size of it. For instance I really just want to create a list of matrices but why do I need to specify whether it's a list of 2x2 matrices as apposed to 5x2 matrices and unless I preadvise the code, in the np.empty statement, it brings up an error.
Update: Here is the output I get. https://images.kiwiheretic.xyz/jupyter-output1.png
Is numpy really this rigid as python lists are not nearly as fussy?