Home  >  Article  >  Backend Development  >  How to Convert a List of Lists into a NumPy Array?

How to Convert a List of Lists into a NumPy Array?

DDD
DDDOriginal
2024-10-20 13:01:30565browse

How to Convert a List of Lists into a NumPy Array?

Converting List of Lists into Numpy Array

When working with Python, you may encounter situations where you need to convert data structures like lists into NumPy arrays. Specifically, when dealing with a list of lists, the goal is to transform it into a NumPy array where each row represents one of the sublists, with elements from that sublist as entries in that row.

Solution

To achieve this conversion, consider the following options:

1. Array of Arrays

If the sublists have varying lengths, create an array of arrays:

<code class="python">x = [[1, 2], [1, 2, 3], [1]]
y = numpy.array([numpy.array(xi) for xi in x])</code>

2. Array of Lists

Alternatively, you can create an array of lists:

<code class="python">x = [[1, 2], [1, 2, 3], [1]]
y = numpy.array(x)</code>

3. Padding Sublists

If you want an array where all rows have the same length, first make the sublists equal in length:

<code class="python">x = [[1, 2], [1, 2, 3], [1]]
length = max(map(len, x))
y = numpy.array([xi + [None] * (length - len(xi)) for xi in x])</code>

By implementing these methods, you can successfully convert a list of lists into a NumPy array to facilitate further numerical operations and data analysis.

The above is the detailed content of How to Convert a List of Lists into a NumPy Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn