How do you convert a Pandas DataFrame back into a list of lists?

Susan Sarandon
Release: 2024-10-29 22:14:30
Original
887 people have browsed it

How do you convert a Pandas DataFrame back into a list of lists?

Transforming Pandas DataFrame into a List of Lists

In the realm of pandas, it is a seamless task to convert a list of lists into a structured DataFrame using the DataFrame constructor. However, the reverse operation, turning a DataFrame back into a list of lists, poses a slight challenge.

To reclaim the list of lists from a DataFrame (df), access its underlying array (df.values) and invoke the tolist method. This method efficiently transforms the array into a nested list representation.

Below is a code snippet that demonstrates the process:

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

df = pd.DataFrame([[1, 2, 3], [3, 4, 5]])
lol = df.values.tolist()

print(lol)
# [[1, 2, 3], [3, 4, 5]]</code>
Copy after login

As illustrated in the code, df.values.tolist() retrieves the list of lists and stores it in lol. The resulting lol variable holds the original data in its list of lists format.

The above is the detailed content of How do you convert a Pandas DataFrame back into 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