Converting a List of Lists into Numpy Array
When working with nested data structures in Python, it often becomes necessary to convert them into a more structured format like a Numpy array. To convert a list of lists into a Numpy array, where each row represents an individual sublist and contains its elements, several approaches can be employed.
One method involves creating an array of arrays, where each element in the outer array is itself an array containing the contents of the corresponding sublist in the original list of lists. Here's an example:
x = [[1, 2], [1, 2, 3], [1]]
y = numpy.array([numpy.array(xi) for xi in x])
Alternatively, one can create an array of lists, where the outer array contains the sublists themselves as elements.
x = [[1, 2], [1, 2, 3], [1]]
y = numpy.array(x)
In cases where the sublists vary in length, it's possible to equalize their lengths by padding shorter sublists with None values before converting them into a Numpy array.
x = [[1, 2], [1, 2, 3], [1]]
length = max(map(len, x))
y = numpy.array([xi [None] * (length - len(xi)) for xi in x])
Which method to choose depends on the specific requirements of the task. These approaches provide a comprehensive understanding of how to convert a list of lists into a Numpy array, enabling efficient data manipulation in Python.
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