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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 10:25:31246browse

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

Reversing the Conversion: DataFrame to List of Lists

While the conversion from a list of lists to a Pandas DataFrame is straightforward, the reverse process can be a bit puzzling. This article demonstrates how to efficiently transform a DataFrame back into its original list of lists format.

The Challenge

Suppose you have a Pandas DataFrame constructed from a list of lists, as shown below:

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

df = pd.DataFrame([[1, 2, 3], [3, 4, 5]])</code>

The question arises: how do we convert df back into its constituent list of lists?

The Solution

The key to reversing this conversion lies in accessing the DataFrame's underlying NumPy array and utilizing its tolist() method.

<code class="python">lol = df.values.tolist()

print(lol)  # Outputs: [[1, 2, 3], [3, 4, 5]]</code>

By leveraging this approach, you can effortlessly convert your DataFrame into a list of lists, enabling further data manipulation or conversion into other desired formats.

The above is the detailed content of How to Convert a Pandas DataFrame Back 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