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

DDD
Release: 2024-10-20 13:01:30
Original
564 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!