Retrieve a Single Value From A DataFrame
To explore the different ways to retrieve a single value from a pandas DataFrame, we'll be looking at a DataFrame of different NBA basketball teams.
import pandas as pd
# Creates a DataFrame with 'state', 'valuation', and 'championships' columns:
df = pd.DataFrame([
{'team': 'Chicago Bulls', 'state': 'Illinois', 'valuation': 3650000000, 'championships': 6},
{'team': 'Golden State Warriors', 'state': 'California', 'valuation': 5600000000, 'championships': 6},
{'team': 'Los Angeles Lakers', 'state': 'California', 'valuation': 5500000000, 'championships': 17},
{'team': 'Boston Celtics', 'state': 'Massachusetts', 'valuation': 3100000000, 'championships': 17},
{'team': 'Miami Heat', 'state': 'Florida', 'valuation': 1750000000, 'championships': 3},
])
# Set the row label indexes to use the "team" column:
df.set_index('team', inplace = True)
df
state | valuation | championships | |
---|---|---|---|
team | |||
Chicago Bulls | Illinois | 3650000000 | 6 |
Golden State Warriors | California | 5600000000 | 6 |
Los Angeles Lakers | California | 5500000000 | 17 |
Boston Celtics | Massachusetts | 3100000000 | 17 |
Miami Heat | Florida | 1750000000 | 3 |
Retrieve a Single Value using at
A common function used to retrieve single values from a DataFrame is the at
function, which uses a label pair of row and column to specify the cell.
This function only accepts row labels (e.g. Chicago Bulls
) as its input. This means that integers (e.g. 0
) are treated as row labels, not index positions. For this function, the row label must come first, followed by the column label.
In addition to getting values, we can use the at
function to change the value stored in a cell.
For example, the Golden State Warriors won the 2021-2022 NBA Championship, and the team now has 7 championship titles:
Now, the Golden State Warriors' championships
column contains the value 7
instead of 6
:
# printing df
df
state | valuation | championships | |
---|---|---|---|
team | |||
Chicago Bulls | Illinois | 3650000000 | 6 |
Golden State Warriors | California | 5600000000 | 7 |
Los Angeles Lakers | California | 5500000000 | 17 |
Boston Celtics | Massachusetts | 3100000000 | 17 |
Miami Heat | Florida | 1750000000 | 3 |
Retrieve a Single Value using iat
Another way to retrieve a single value from a pandas DataFrame is to use the iat
function.
The iat
function is similar to the at
function, except that it only accepts integers indexes (e.g. 0
, 1
...) as its input.
Retrieve a Single Value using loc
We can also find a single cell value using the loc
function to specify the row using a label followed by the column label enclosed in brackets ([]
):
Retrieve a Single Value using iloc
We can also use integer positions instead of labels to specify the row. To do this, we would use the iloc
function:
Pandas Documentation
Click Here for the full pandas documentation for the at
function
Click Here for the full pandas documentation for the iat
function