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.
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.
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.
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!