Home > Backend Development > Python Tutorial > How do I convert a Pandas DataFrame back to a list of lists?

How do I convert a Pandas DataFrame back to a list of lists?

Patricia Arquette
Release: 2024-11-03 02:56:02
Original
416 people have browsed it

How do I convert a Pandas DataFrame back to a list of lists?

Reversing the Transformation: Converting a Pandas DataFrame to a List of Lists

It is straightforward to create a pandas DataFrame from a list of lists. However, converting a DataFrame back to a list of lists requires a different approach. This question examines the methods for extracting the data from a DataFrame and converting it into the desired format.

To achieve the conversion, the following steps can be taken:

  1. Retrieving the Underlying Array:

    • The DataFrame has an underlying NumericalPython (NumPy) array that stores the data. To access this array, use the df.values attribute.
  2. Converting to a List:

    • Apply the tolist method on the obtained NumPy array to convert it into a list of lists.

For example:

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

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

# Extract the underlying NumPy array
array = df.values

# Convert to a list of lists
list_of_lists = array.tolist()

# Print the result
print(list_of_lists)
# Output: [[1, 2, 3], [3, 4, 5]]</code>
Copy after login

By following these steps, you can effectively convert a pandas DataFrame back to a list of lists, retaining the original data.

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