Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list of lists with different lengths to a numpy array [duplicate]

Tags:

I have list of lists with different lengths (e.g. [[1, 2, 3], [4, 5], [6, 7, 8, 9]]) and want to convert it into a numpy array of integers. I understand that 'sub' arrays in numpy multidimensional array must be the same length. So what is the most efficient way to convert such a list as in example above into a numpy array like this [[1, 2, 3, 0], [4, 5, 0, 0], [6, 7, 8, 9]], i.e. completed with zeros?

like image 284
Dimansel Avatar asked Mar 31 '17 17:03

Dimansel


People also ask

Can you convert a list to a NumPy array?

Lists can be converted to arrays using the built-in functions in the Python numpy library. numpy provides us with two functions to use when converting a list into an array: numpy. array()

Can NumPy arrays be multidimensional?

In general numpy arrays can have more than one dimension. One way to create such array is to start with a 1-dimensional array and use the numpy reshape() function that rearranges elements of that array into a new shape.

How much faster are NumPy arrays than lists?

Because the Numpy array is densely packed in memory due to its homogeneous type, it also frees the memory faster. So overall a task executed in Numpy is around 5 to 100 times faster than the standard python list, which is a significant leap in terms of speed.


1 Answers

you could make a numpy array with np.zeros and fill them with your list elements as shown below.

a = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] import numpy as np b = np.zeros([len(a),len(max(a,key = lambda x: len(x)))]) for i,j in enumerate(a):     b[i][0:len(j)] = j 

results in

[[ 1.  2.  3.  0.]  [ 4.  5.  0.  0.]  [ 6.  7.  8.  9.]] 
like image 177
plasmon360 Avatar answered Oct 04 '22 10:10

plasmon360