Home > Backend Development > Python Tutorial > How to Convert Lists of Lists with Variable Lengths into a Numpy Array in Python?

How to Convert Lists of Lists with Variable Lengths into a Numpy Array in Python?

DDD
Release: 2024-10-20 13:11:30
Original
251 people have browsed it

How to Convert Lists of Lists with Variable Lengths into a Numpy Array in Python?

Converting a List of Lists to a Numpy Array

In Python, a common task is to manipulate data stored in lists of lists. Sometimes, it becomes necessary to convert this data into a structured format like a Numpy array for efficient processing. Here, we discuss different approaches to perform this conversion when the individual sublists have varying lengths.

1. Creating an Array of Arrays

Sublists of varying lengths can be stored as an array of arrays. Each sublist is converted to a Numpy array, and then these arrays are combined into a larger array:

<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. Creating an Array of Lists

An array of lists can be created by simply converting the list of lists directly to a Numpy array:

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

3. Equalizing List Lengths

If the desired result is a Numpy array with equal row lengths, the sublists can be padded with None values:

<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

Each of these approaches provides a way to convert a list of lists with varying lengths into a Numpy array, depending on the specific requirements and desired data structure.

The above is the detailed content of How to Convert Lists of Lists with Variable Lengths into a Numpy Array in Python?. 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