October 13, 2024

Convert DataFrame into List in Python

In Python, you can convert a pandas DataFrame into a list in various formats depending on your needs. Below are some common methods to achieve this using the pandas library.

1. Convert DataFrame to List of Lists

This method converts each row of the DataFrame into a list and returns a list of these lists.

import pandas as pd

# Create a 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

This method converts each row of the DataFrame into a dictionary, where the keys are the column names and the values are the data from the rows. It returns a list of these dictionaries.

# Convert DataFrame to list of dictionaries
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

This method extracts the values of a specific column as a list. You can repeat this for each column if needed.

# Convert specific column to list
column_list = df['A'].tolist()
print(column_list)
    

Output:

[1, 2, 3]
    

4. Convert DataFrame to List of Row Values

To get a list of values for a specific row:

# Convert specific row to list
row_list = df.iloc[1].tolist()  # Index 1 corresponds to the second row
print(row_list)
    

Output:

[2, 5]
    

5. Conclusion

Converting a DataFrame to a list can be useful for various data manipulation tasks. Depending on whether you need the data in rows, columns, or dictionary format, you can use the methods outlined above. The pandas library provides flexible options for data conversion and manipulation.