Converting a List of Lists to a Numpy Array
In Python, a common task is to manipulate data stored in lists of lists. Sometimes, it becomes necessary to convert this data into a structured format like a Numpy array for efficient processing. Here, we discuss different approaches to perform this conversion when the individual sublists have varying lengths.
1. Creating an Array of Arrays
Sublists of varying lengths can be stored as an array of arrays. Each sublist is converted to a Numpy array, and then these arrays are combined into a larger array:
x=[[1,2],[1,2,3],[1]]
y=numpy.array([numpy.array(xi) for xi in x])
2. Creating an Array of Lists
An array of lists can be created by simply converting the list of lists directly to a Numpy array:
x=[[1,2],[1,2,3],[1]]
y=numpy.array(x)
3. Equalizing List Lengths
If the desired result is a Numpy array with equal row lengths, the sublists can be padded with None values:
x=[[1,2],[1,2,3],[1]]
length = max(map(len, x))
y=numpy.array([xi [None]*(length-len(xi)) for xi in x])
Each of these approaches provides a way to convert a list of lists with varying lengths into a Numpy array, depending on the specific requirements and desired data structure.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3