How to Create a DataFrame in Python
What you’ll build or solve
A DataFrame is a two-dimensional labeled table, with rows and named columns, from the pandas library. You create one by passing your data to pd.DataFrame():
Python
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Chen"],
"age": [28, 34, 25],
})
print(df)
Output:
Learn Python on Mimo
name age
0 Ana 28
1 Ben 34
2 Chen 25
The rest of this page shows how to build a DataFrame from other input shapes, how to inspect it quickly, and how to load a short CSV file.
When this approach works best
This approach works best when you:
- Have tabular data, like products, scores, or survey answers, that you want to label by column.
- Want to inspect, filter, or summarize that data with pandas.
Avoid this approach when:
- You only have a handful of values. A plain list or dictionary may be enough.
- Your file is too large to fit in memory. You may need chunked processing or a database.
Prerequisites
- Python 3.11 or newer (pandas 3.x requires it). The outputs on this page come from Python 3.13 and pandas 3.1.1.
- pandas installed:
Bash
python -m pip install pandas
- You know what a list and a dictionary are.
Step-by-step instructions
1) Import pandas
Import pandas with the short name pd. Most pandas code and documentation uses this alias.
Python
import pandas as pd
If this line raises ModuleNotFoundError, install pandas first. See Troubleshooting below.
2) Create a DataFrame from a dictionary of lists
This is the most common way to create a DataFrame. Each key becomes a column name, and each list holds the values for that column.
Python
import pandas as pd
data = {
"product": ["Notebook", "Pen", "Backpack"],
"price": [4.5, 1.2, 39.9],
"in_stock": [True, True, False],
}
df = pd.DataFrame(data)
print(df)
Output:
product price in_stock
0 Notebook 4.5 True
1 Pen 1.2 True
2 Backpack 39.9 False
What to look for:
- The columns appear in the same order as the keys in your dictionary. See the
pandas.DataFramereference. - The numbers
0,1,2on the left are the row labels. pandas adds them by default when you don’t pass anindex. - Every list must have the same length, one value per row.
3) Create a DataFrame from a list of dictionaries
Use this when your data arrives one record at a time, like rows from an API or a loop. Each dictionary becomes one row. The population figures are sample data for this example, not sourced statistics.
Python
import pandas as pd
rows = [
{"city": "Lisbon", "country": "Portugal", "population": 545000},
{"city": "Vienna", "country": "Austria", "population": 2006000},
{"city": "Oslo", "country": "Norway", "population": 717000},
]
df = pd.DataFrame(rows)
print(df)
Output:
city country population
0 Lisbon Portugal 545000
1 Vienna Austria 2006000
2 Oslo Norway 717000
What to look for:
The dictionary keys become column names, in the order the keys first appear.
4) Create a DataFrame from a list of lists
Use this when each row is a plain list of values. Pass the column names with columns=.
Python
import pandas as pd
rows = [
["Ana", "Math", 91],
["Ben", "History", 78],
["Chen", "Biology", 85],
]
df = pd.DataFrame(rows, columns=["student", "subject", "score"])
print(df)
Output:
student subject score
0 Ana Math 91
1 Ben History 78
2 Chen Biology 85
What to look for:
If you leave out columns=, pandas labels the columns 0, 1, 2, and so on. See Common mistakes below.
5) Inspect the DataFrame
After you create a DataFrame, check that it looks the way you expect.
Python
import pandas as pd
df = pd.DataFrame({
"product": ["Notebook", "Pen", "Backpack", "Mug", "Stapler", "Lamp"],
"price": [4.5, 1.2, 39.9, 8.0, 12.5, 24.0],
"in_stock": [True, True, False, True, False, True],
})
print(df.head())
print(df.shape)
print(df.columns)
print(df.dtypes)
Output:
product price in_stock
0 Notebook 4.5 True
1 Pen 1.2 True
2 Backpack 39.9 False
3 Mug 8.0 True
4 Stapler 12.5 False
(6, 3)
Index(['product', 'price', 'in_stock'], dtype='str')
product str
price float64
in_stock bool
dtype: object
What to look for:
head()shows the first five rows. Pass a number, likehead(10), to see more.shapeis(rows, columns). Here the DataFrame has 6 rows and 3 columns.columnslists the column names.dtypesshows the type of each column. Text columns show asstr, decimals asfloat64, andTrue/Falsevalues asbool.
6) Create a DataFrame from a CSV file
When your data is already in a file, pd.read_csv() reads it straight into a DataFrame.
Save this as scores.csv in your current working directory, the folder you run Python from:
name,city,score
Ana,Lisbon,91
Ben,Vienna,78
Chen,Oslo,85
Dara,Madrid,88
Then read it:
Python
import pandas as pd
df = pd.read_csv("scores.csv")
print(df)
Output:
name city score
0 Ana Lisbon 91
1 Ben Vienna 78
2 Chen Oslo 85
3 Dara Madrid 88
The first line of the file becomes the column names. To go further with loading, cleaning, and analyzing data, see How to Use Pandas in Python.
Common mistakes and how to fix them
Mistake 1: Passing lists of different lengths in a dictionary
You might write:
Python
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Chen"],
"age": [28, 34],
})
You’ll see:
ValueError: All arrays must be of the same length
Why it breaks:
When the dictionary values are plain lists, pandas needs one value per row in every list. Here name has three values and age has two.
Correct approach:
Make the lists the same length. Use None for a missing value:
Python
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Chen"],
"age": [28, 34, None],
})
print(df)
Output:
name age
0 Ana 28.0
1 Ben 34.0
2 Chen NaN
pandas shows the missing value as NaN, and the age column becomes float64 so it can hold it.
Mistake 2: Forgetting columns= for a list of lists
You might write:
Python
import pandas as pd
rows = [
["Ana", "Math", 91],
["Ben", "History", 78],
["Chen", "Biology", 85],
]
df = pd.DataFrame(rows)
print(df)
Output:
0 1 2
0 Ana Math 91
1 Ben History 78
2 Chen Biology 85
Why it breaks:
A plain list has no names, so pandas numbers the columns. Code like df["score"] then fails because there is no score column.
Correct approach:
Pass the names with columns=, as in step 4. With the same rows list:
Python
import pandas as pd
rows = [
["Ana", "Math", 91],
["Ben", "History", 78],
["Chen", "Biology", 85],
]
df = pd.DataFrame(rows, columns=["student", "subject", "score"])
print(df)
Output:
student subject score
0 Ana Math 91
1 Ben History 78
2 Chen Biology 85
Mistake 3: Using df.append() from older tutorials
You might write:
Python
import pandas as pd
df = pd.DataFrame({"name": ["Ana"], "age": [28]})
df = df.append({"name": "Ben", "age": 34}, ignore_index=True)
You’ll see:
AttributeError: 'DataFrame' object has no attribute 'append'
Why it breaks:
DataFrame.append() was removed in pandas 2.0. See the pandas 2.0 release notes.
Correct approach:
Collect your rows in a list first, then create the DataFrame once:
Python
import pandas as pd
rows = []
rows.append({"name": "Ana", "age": 28})
rows.append({"name": "Ben", "age": 34})
df = pd.DataFrame(rows)
print(df)
Output:
name age
0 Ana 28
1 Ben 34
If you already have two DataFrames, combine them with pd.concat():
Python
import pandas as pd
df1 = pd.DataFrame({"name": ["Ana"], "age": [28]})
df2 = pd.DataFrame({"name": ["Ben"], "age": [34]})
df = pd.concat([df1, df2], ignore_index=True)
print(df)
Output:
name age
0 Ana 28
1 Ben 34
Troubleshooting
If you see ModuleNotFoundError: No module named 'pandas', install pandas with python -m pip install pandas. If python is not found, use python3 -m pip install pandas.
If you see AttributeError: 'DataFrame' object has no attribute 'append', build a list of rows and call pd.DataFrame(rows), or use pd.concat() to combine existing DataFrames.
Quick recap
- Import pandas with
import pandas as pd. - Create a DataFrame from a dictionary of lists, where each key becomes a column.
- Create one from a list of dictionaries, where each dictionary becomes a row.
- Create one from a list of lists, and pass the column names with
columns=. - Check the result with
head(),shape,columns, anddtypes. - Load a CSV file into a DataFrame with
pd.read_csv().
Join 40M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot