David Y.
—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.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,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.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.