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.
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.
Get actionable, code-level insights to resolve Python performance bottlenecks and errors.
Create a free Sentry account
Create a Python project and note your DSN
Grab the Sentry Python SDK
pip install --upgrade sentry-sdk
import sentry_sdk sentry_sdk.init( "https://<key>@sentry.io/<project>", # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production. traces_sample_rate=1.0, )
Loved by over 4 million developers and more than 90,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.