Convert a Pandas DataFrame to a List

Authors

Convert Pandas DataFrame To A List

Pandas is a powerful and versatile library for data manipulation and analysis in Python.

One of its key features is the DataFrame, a two-dimensional table-like structure that can hold data of various types and allows for flexible indexing and slicing.

In many cases, we may need to convert a DataFrame to a Python list.

This can be done using the to_dict() method, which returns a dictionary of the DataFrame's rows and columns.

We can then use the values() method to extract the values as a list.

Here's an example of converting a DataFrame to a list:

import pandas as pd

# Create a sample DataFrame
data = {'name': ['John', 'Mary', 'Paul'], 'age': [25, 22, 30]}
df = pd.DataFrame(data)

# Convert DataFrame to list
list_data = df.to_dict().values()

print(list_data)

Output:

[{'name': 'John', 'age': 25}, {'name': 'Mary', 'age': 22}, {'name': 'Paul', 'age': 30}]

We can also convert specific columns of a DataFrame to a list using the tolist() method.

# convert specific column to list
age_list = df['age'].tolist()
print(age_list)

Output:

[25, 22, 30]

In this way, we can convert a DataFrame to a list in pandas.

This can be useful when we need to work with the data in a list format, such as when we need to pass it to a machine learning algorithm or a visualization library that doesn't support DataFrames.

TrackingJoy