How to Create DataFrame from List in pandas - Simple Guide
To create a
DataFrame from a list in pandas, use pd.DataFrame() and pass your list as the data argument. You can also specify column names with the columns parameter to label your data.Syntax
The basic syntax to create a DataFrame from a list is:
pd.DataFrame(data, columns=None)
Where:
datais your list (can be a list of values or list of lists).columnsis an optional list of column names to label the DataFrame.
python
import pandas as pd # Syntax pattern pd.DataFrame(data, columns=None)
Example
This example shows how to create a DataFrame from a simple list and a list of lists, with column names.
python
import pandas as pd # Create DataFrame from a simple list simple_list = [10, 20, 30, 40] df_simple = pd.DataFrame(simple_list, columns=['Numbers']) # Create DataFrame from a list of lists list_of_lists = [[1, 'Alice'], [2, 'Bob'], [3, 'Charlie']] df_complex = pd.DataFrame(list_of_lists, columns=['ID', 'Name']) print(df_simple) print(df_complex)
Output
Numbers
0 10
1 20
2 30
3 40
ID Name
0 1 Alice
1 2 Bob
2 3 Charlie
Common Pitfalls
Common mistakes include:
- Not passing a list of lists when you want multiple columns, which causes a single column DataFrame.
- Forgetting to specify
columnswhen your data has multiple elements per row, resulting in default numeric column names. - Passing a list of unequal length elements, which raises errors.
python
import pandas as pd # Wrong: list of values but expecting multiple columns data_wrong = [1, 2, 3] # The following line will raise a ValueError because the data is 1D but columns has length 2 # df_wrong = pd.DataFrame(data_wrong, columns=['A', 'B']) # Error # Right: list of lists with matching columns data_right = [[1, 10], [2, 20], [3, 30]] df_right = pd.DataFrame(data_right, columns=['A', 'B']) print(df_right)
Output
A B
0 1 10
1 2 20
2 3 30
Quick Reference
Summary tips for creating DataFrames from lists:
- Use
pd.DataFrame()with your list as data. - For multiple columns, use a list of lists and specify
columns. - Check your data shape matches the columns length.
- Simple lists create single-column DataFrames.
Key Takeaways
Use pd.DataFrame() to convert a list into a DataFrame easily.
For multiple columns, pass a list of lists and specify column names.
Simple lists create single-column DataFrames by default.
Always ensure your data shape matches the number of columns.
Missing or mismatched columns cause errors or default column names.