Here are several ways to convert DataFrame to List in Pandas:
- DataFrame column to list
- DataFrame to a nested list
- DataFrame into a nested list of columns
- DataFrame to list with column names
Here is the sample DataFrame that we will use to convert different types of lists:
import pandas as pd
# Example DataFrame
df = pd.DataFrame({'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]})
print(df)
Output
Approach 1: DataFrame column to list
To convert a single DataFrame column to a list, you can simply use the tolist() method on the DataFrame column.
This approach is great for extracting a single column as a list.
import pandas as pd
# Example DataFrame
df = pd.DataFrame({'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]})
# Convert column 'A' to list
list_A = df['A'].tolist()
print(list_A)
Output
[1, 2, 3]
Approach 2: DataFrame to nested list
To convert the entire DataFrame into a nested list (where each row is a list), you can use the .values attribute followed by the tolist() method.
This approach helps get a row-wise nested list representation of the DataFrame.
import pandas as pd
# Example DataFrame
df = pd.DataFrame({'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]})
# Convert entire DataFrame to nested list
nested_list = df.values.tolist()
print(nested_list)
Output
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Approach 3: DataFrame to nested list
To convert the DataFrame to a nested list where each inner list contains the values of a specific column, you can use list comprehension.
This approach is good for column-wise conversion to nested lists.
import pandas as pd
# Example DataFrame
df = pd.DataFrame({'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]})
# Convert DataFrame into nested list of columns
nested_list_columns = [df[col].tolist() for col in df.columns]
print(nested_list_columns)
Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Approach 4: DataFrame to list with column names
To include column names in your list, you can iterate over DataFrame rows and convert each row to a dictionary with to_dict(), consisting of column names as keys.
This approach provides a list of dictionaries, preserving data and column names, which is helpful for specific applications like JSON conversion or when column context is important.
import pandas as pd
# Example DataFrame
df = pd.DataFrame({'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]})
# Convert DataFrame to list of dictionaries
list_with_column_names = df.to_dict(orient='records')
print(list_with_column_names)
Output
[{'A': 1, 'B': 4, 'C': 7}, {'A': 2, 'B': 5, 'C': 8}, {'A': 3, 'B': 6, 'C': 9}]
That’s all!
R A
Thanks a lot Sir, you are genius
threadsGuy
This is a great post! I was wondering how to do the same thing with my dataframe.