"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Convert a List of Lists into a Uniform NumPy Array?

How Can I Convert a List of Lists into a Uniform NumPy Array?

Published on 2024-11-06
Browse:273

How Can I Convert a List of Lists into a Uniform NumPy Array?

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])
Release Statement This article is reprinted at: 1729400417 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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