Home  >  Article  >  Backend Development  >  How to Convert a Pandas DataFrame to a List of Lists?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-30 11:56:26429browse

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>

Output:

[[1, 2, 3], [3, 4, 5]]

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!

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