TExcelTAD
Home › pandas › Pandas DataFrames

Pandas DataFrames

A DataFrame is a two-dimensional table: rows and columns, each column a Series, all sharing the same row index. It is the object you will spend most of your pandas time with.

Creating a DataFrame from a dictionary

The most common way to build one by hand is a dictionary of lists, one list per column:

python · try it yourself
import pandas as pd

books = pd.DataFrame({
    "title": ["Dune", "Emma", "Ulysses", "Beloved"],
    "year": [1965, 1815, 1922, 1987],
    "pages": [412, 474, 730, 324],
})
print(books)
     title  year  pages
0     Dune  1965    412
1     Emma  1815    474
2  Ulysses  1922    730
3  Beloved  1987    324

All lists must have the same length. Each key becomes a column name, and pandas adds the default index 0, 1, 2, 3.

Other ways to build one

python · try it yourself
import pandas as pd

# A list of dictionaries: one dictionary per row
rows = [
    {"planet": "Mercury", "moons": 0},
    {"planet": "Earth", "moons": 1},
    {"planet": "Mars", "moons": 2},
]
print(pd.DataFrame(rows))

# A list of lists plus column names
grid = [["A1", 3.5], ["B7", 1.25]]
print(pd.DataFrame(grid, columns=["seat", "price"]))
    planet  moons
0  Mercury      0
1    Earth      1
2     Mars      2
  seat  price
0   A1   3.50
1   B7   1.25

The list-of-dictionaries form is handy for data that arrives one record at a time, for example from a web API.

Selecting columns

Use the column name in square brackets. One name gives a Series; a list of names gives a smaller DataFrame:

python · try it yourself
import pandas as pd

books = pd.DataFrame({
    "title": ["Dune", "Emma", "Ulysses", "Beloved"],
    "year": [1965, 1815, 1922, 1987],
    "pages": [412, 474, 730, 324],
})
print(books["pages"])
print(type(books["pages"]).__name__)
print(books[["title", "year"]])
0    412
1    474
2    730
3    324
Name: pages, dtype: int64
Series
     title  year
0     Dune  1965
1     Emma  1815
2  Ulysses  1922
3  Beloved  1987

Tip: You may also see books.pages (attribute access). It works for simple names but fails for names with spaces or names that clash with methods such as count, so the bracket form is safer.

Selecting rows with loc and iloc

loc selects rows by label; iloc selects by integer position. With the default index the two look alike, so let's give the frame a meaningful index:

python · try it yourself
import pandas as pd

books = pd.DataFrame({
    "year": [1965, 1815, 1922, 1987],
    "pages": [412, 474, 730, 324],
}, index=["Dune", "Emma", "Ulysses", "Beloved"])

print(books.loc["Emma"])
print(books.iloc[0])
print(books.loc[["Dune", "Beloved"]])
year     1815
pages     474
Name: Emma, dtype: int64
year     1965
pages     412
Name: Dune, dtype: int64
         year  pages
Dune     1965    412
Beloved  1987    324

A single row comes back as a Series whose index is the column names. A list of labels returns a DataFrame. A whole lesson later in the course is devoted to loc and iloc.

Basic properties

python · try it yourself
import pandas as pd

books = pd.DataFrame({
    "title": ["Dune", "Emma", "Ulysses", "Beloved"],
    "year": [1965, 1815, 1922, 1987],
    "pages": [412, 474, 730, 324],
})
print(books.shape)
print(list(books.columns))
print(books.index)
print(books.dtypes)
(4, 3)
['title', 'year', 'pages']
RangeIndex(start=0, stop=4, step=1)
title    object
year      int64
pages     int64
dtype: object
Attribute Meaning
df.shape (rows, columns)
df.columns column labels
df.index row labels
df.dtypes data type of every column
df.size total number of cells

Text columns show the dtype object, the general-purpose type pandas uses for Python strings.

Adding a column

Assigning to a new column name creates it. The right-hand side can be a single value or a calculation on other columns:

python · try it yourself
import pandas as pd

books = pd.DataFrame({
    "title": ["Dune", "Emma", "Ulysses", "Beloved"],
    "year": [1965, 1815, 1922, 1987],
    "pages": [412, 474, 730, 324],
})
books["age"] = 2025 - books["year"]
books["format"] = "paperback"
print(books)
     title  year  pages  age     format
0     Dune  1965    412   60  paperback
1     Emma  1815    474  210  paperback
2  Ulysses  1922    730  103  paperback
3  Beloved  1987    324   38  paperback

Test yourself

What does df["price"] return?

  1. A DataFrame
  2. A Series
  3. A list
  4. A NumPy matrix

Which accessor selects rows by integer position?

  1. loc
  2. iloc
  3. at
  4. ix

When building a DataFrame from a dictionary of lists, what becomes the column names?

  1. The list values
  2. The dictionary keys
  3. The numbers 0, 1, 2…
  4. Nothing; you must pass columns=