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():

import pandas as pd

df = pd.DataFrame({
    "name": ["Ana", "Ben", "Chen"],
    "age": [28, 34, 25],
})
print(df)

Output:

   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:
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.

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.

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.DataFrame reference.
  • The numbers 0, 1, 2 on the left are the row labels. pandas adds them by default when you don’t pass an index.
  • 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.

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=.

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.

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, like head(10), to see more.
  • shape is (rows, columns). Here the DataFrame has 6 rows and 3 columns.
  • columns lists the column names.
  • dtypes shows the type of each column. Text columns show as str, decimals as float64, and True/False values as bool.

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:

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:

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:

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:

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:

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:

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:

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():

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, and dtypes.
  • Load a CSV file into a DataFrame with pd.read_csv().