To convert a dataframe to a list in Pandas, you can use the df.values.tolist() function where each inner list represents a row.
Example
import pandas as pd
# create a sample dataframe
df = pd.DataFrame({
'name': ['John', 'Smith', 'Sarah'],
'age': [25, 30, 32],
'city': ['New York', 'London', 'Paris']
})
# convert dataframe to list
df_list = df.values.tolist()
print(df_list)
Output
[['John', 25, 'New York'], ['Smith', 30, 'London'], ['Sarah', 32, 'Paris']]
Converting Pandas Column to List
To convert a pandas DataFrame column to a list, you can use the tolist() method after selecting the desired column.
import pandas as pd
# create a sample dataframe
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
df = pd.DataFrame(data)
# Convert a column to a list
column_A_list = df['A'].tolist()
print("Column A as list:", column_A_list)
Output
Column A as list: [1, 2, 3]
In this example, a DataFrame df is created using dictionary data.
To convert column ‘A’ to a list, you can use the tolist() method on the selected column like this: df[‘A’].tolist(). The resulting list is stored in the column_A_list variable and then printed.
Converting DataFrame to Nested List
To convert a DataFrame to a nested list (a list of lists, where each inner list represents a row), you can use the values attribute followed by the tolist() method.
import pandas as pd
# create a sample dataframe
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
df = pd.DataFrame(data)
# Convert a column to a list
nested_list = df.values.tolist()
print("Nested list:", nested_list)
Output
Nested list: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
In this example, a DataFrame df is created using dictionary data.
To convert the entire DataFrame to a nested list, you can use the values attribute to get a NumPy array-like representation of the DataFrame and then call the tolist() method on it: df.values.tolist().
The resulting nested list is stored in the nested_list variable and then printed.
Converting Pandas Index Column to List
To convert a DataFrame’s index column to a list, you can use the tolist() method on the DataFrame’s index attribute.
import pandas as pd
# create a sample dataframe
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
index_values = ['row1', 'row2', 'row3']
df = pd.DataFrame(data, index=index_values)
# Convert index column to a list
index_list = df.index.tolist()
print("Index column as list:", index_list)
Output
Index column as list: ['row1', 'row2', 'row3']
In this example, a DataFrame df is created using dictionary data and custom index values index_values. To convert the index column to a list, you can use the tolist() method on the DataFrame’s index attribute like this: df.index.tolist(). The resulting list is stored in the index_list variable and then printed.
That’s it.
Thanks a lot Sir, you are genius