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?
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()
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.
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.
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.]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With