Converting a List of Lists into a NumPy Array
A common task in data analysis is converting a list of lists into a NumPy array for efficient numerical operations. This array can be formed by assigning each list to a row, with each element in the list occupying a column.
Option 1: Array of Arrays
If the sublists have varying lengths, a suitable approach is to create an array of arrays. This preserves the original structure of the list of lists, making it easy to retrieve specific elements or perform operations on individual sublists.
x = [[1, 2], [1, 2, 3], [1]]
y = numpy.array([numpy.array(xi) for xi in x])
Option 2: Array of Lists
An alternative method is to create an array of lists. This approach maintains the structure of the list of lists, with each sublist represented as a list within the array.
x = [[1, 2], [1, 2, 3], [1]]
y = numpy.array(x)
Option 3: Uniform List Lengths
If it's essential that the sublists have uniform lengths, it's possible to pad shorter lists with None values. This creates a rectangular array with consistent dimensions.
x = [[1, 2], [1, 2, 3], [1]]
length = max(map(len, x))
y = numpy.array([xi [None] * (length - len(xi)) for xi in x])
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