This article was automatically translated from Japanese using AI. The Japanese version is the authoritative version.
Extracting one specific value from a pandas DataFrame in Python is surprisingly tricky.
DataFrames are designed to be handled as DataFrames, so extracting, slicing, or appending rows is very easy.
When you try to pull out a single value, however, for some reason you don’t get the value itself—you end up with a DataFrame, along with various other issues.
Here I describe how to extract the value in a DataFrame that satisfies a particular condition.
There may well be better approaches, but this is the best I can do at the moment.
Suppose we have the DataFrame below and want to extract the value 20 outlined in red.

The problem is that with a simple DataFrame like the one above you can see the index and pull the value out in one step, but with a large dataset it is very hard to check the index number and use it.
With large amounts of data, it is more efficient to extract values using a key column (customer number, id, etc.) as a clue.
So let’s try extracting the value in the situation below.

In other words, we want to extract the value in column B for the row where column A is Aichi.
This cannot be done in a single step; the value is extracted in two stages.
First, create a DataFrame like the one above.
import pandas as pd
df = pd.DataFrame({ 'A' : ["Tokyo", "Aichi", "Osaka"],
'B' : [10, 20, 30],
'C' : [100, 200, 300]})
df

Next, extract the row where column A is Aichi.
a = df[df["A"] == "Aichi"]
print(a)

This lets us extract the row containing Aichi.
Finally, extract the value in column B of that row.
b = a.at[a.index[0], "B"]
print(b)

Doing this, we can extract the value.
It is roundabout, but this is the method I currently use.
If you know of another approach, I would be glad to hear about it in the comments.
import pandas as pd
df = pd.DataFrame({ 'A' : ["Tokyo", "Aichi", "Osaka"],
'B' : [10, 20, 30],
'C' : [100, 200, 300]})
a = df[df["A"] == "Aichi"]
b = a.at[a.index[0], "B"]
print(b)
Here is a summary of the program above.
