Thursday, January 23, 2025
HomeConversionsHow to Convert Pandas DataFrame into a List?

How to Convert Pandas DataFrame into a List?

To convert a Pandas DataFrame into a list, you have several options depending on the structure and type of list you want. Here are a few common methods:

1. Convert DataFrame to List of Lists (rows as lists)

Each row of the DataFrame becomes a list.

import pandas as pd

# Sample DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
})

# Convert DataFrame to list of lists
list_of_lists = df.values.tolist()
print(list_of_lists)

Output:

[[1, 4], [2, 5], [3, 6]]

2. Convert DataFrame to List of Dictionaries (each row as a dictionary)

Each row is converted into a dictionary where the column names are keys.

list_of_dicts = df.to_dict(orient='records')
print(list_of_dicts)

Output:

[{'A': 1, 'B': 4}, {'A': 2, 'B': 5}, {'A': 3, 'B': 6}]

3. Convert DataFrame to List of Column Values

If you want to convert the columns into a list of values:

list_of_columns = df['A'].tolist()
print(list_of_columns)

Output:

[1, 2, 3]

4. Convert Entire DataFrame to a Single List (flattened)

If you want to flatten the DataFrame into a single list:

flattened_list = df.values.flatten().tolist()
print(flattened_list)

Output:

[1, 4, 2, 5, 3, 6]

Choose the method that best suits the structure you’re looking for!

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x