How to Convert a Dataframe to a List in Python Without Changing Its Datatype?

Estimated read time 1 min read

To convert a DataFrame to a list in Python without changing its data type, you can use the values.tolist() method provided by the Pandas library. This method converts the DataFrame to a nested list while preserving the data types of the DataFrame columns. Here’s an example:

import pandas as pd

def dataframe_to_list(df):
    return df.values.tolist()

# Example usage
data = {
    'Name': ['John', 'Jane', 'Sam'],
    'Age': [25, 30, 35],
    'City': ['New York', 'London', 'Paris']
df = pd.DataFrame(data)

df_list = dataframe_to_list(df)

In this example, the dataframe_to_list function takes the DataFrame df as a parameter. Inside the function, the values.tolist() method is called on the DataFrame, which converts it to a nested list while preserving the data types.

The resulting df_list variable will contain the DataFrame data in list format. Each row of the DataFrame is represented as a sublist, and the elements of each sublist correspond to the column values of the DataFrame.

Note that although the data types are preserved, the resulting list will contain Python objects instead of NumPy or Pandas data structures.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply