How to Convert a Pandas DataFrame to a List of Lists?

Susan Sarandon
Release: 2024-10-30 11:56:26
Original
443 people have browsed it

How to Convert a Pandas DataFrame to a List of Lists?

Transforming Pandas DataFrames to Lists of Lists

When working with data, it is often necessary to convert between different data structures. This question explores how to convert a pandas DataFrame, a tabular data structure, into a list of lists.

Problem Statement

After creating a DataFrame from a list of lists, the task is to transform it back into its original form. The problem arises because the DataFrame class does not provide a direct method to extract the data as a list of lists.

Solution

To address this issue, the user can access the underlying NumPy array associated with the DataFrame. The values attribute of the DataFrame returns a NumPy array representation of its data. The tolist() method of the NumPy array can then be applied to convert the array into a nested list structure.

Implementation

The following Python code illustrates the solution:

<code class="python">import pandas as pd
import numpy as np

# Create a DataFrame from a list of lists
df = pd.DataFrame([[1, 2, 3], [3, 4, 5]])

# Convert the DataFrame to a list of lists using the underlying NumPy array
lol = df.values.tolist()

# Print the result
print(lol)</code>
Copy after login

Output:

[[1, 2, 3], [3, 4, 5]]
Copy after login

This solution effectively converts the DataFrame back into a list of lists, preserving the original data structure.

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

source:php.cn
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
Latest Articles by Author
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!