Get the value of a DataFrame cell in Python Pandas

David Y.
jump to solution

The Problem

How can I retrieve the value of a single cell in a Python Pandas DataFrame? I want just the value, not a new DataFrame with only one cell.

The Solution

We can retrieve the value of a single DataFrame cell using the DataFrame.at property, providing the row and column labels for the element we want to access:

import pandas

# Set up and print the DataFrame
data = {
    "Product": ["Apple", "Orange", "Pear"],
    "Cost Price": [1, 2, 3],
    "Selling Price": [2, 3, 4],
}
df = pandas.DataFrame(data)
print(df)
print()

# will print:
#   Product  Cost Price  Selling Price
# 0   Apple           1              2
# 1  Orange           2              3
# 2    Pear           3              4

# Retrieve "Pear"
df_cell = df.at[2, "Product"]
print(df_cell)  # will print "Pear"

Note that the value 2 here is being interpreted as a row label, rather than a row number. If we want to access the value of a cell using the indices of its row and column rather than the label, we can use DataFrame.iat:

# Retrieve "Pear"
df_cell = df.iat[2, 0]
print(df_cell) # will print "Pear"

We can also use DataFrame.loc in place of DataFrame.at, or DataFrame.iloc in place of DataFrame.iat:

# Retrieve "Pear"
df_cell = df.loc[2, "Product"]
print(df_cell)  # will print "Pear"

# Retrieve "Pear"
df_cell_by_index = df.iloc[2, 0]
print(df_cell_by_index)  # will print "Pear"

DataFrame.loc and DataFrame.iloc are more flexible, general accessors, which can both be used to select arbitrarily sized portions of a DataFrame. DataFrame.at and DataFrame.iat, on the other hand, are both optimized for retrieving the value of a single cell, so the versions of our code using one of these functions will run faster. This will be especially noticeable with large DataFrames.

Read user input (STDIN) in Python
David Y.
Select multiple columns in Python Pandas
David Y.

Considered "not bad" by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world's best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Sentry