This thread doesn't seem to cover a situation I am routinely in.
Return single cell value from Pandas DataFrame
How does one return a single value, not a series or dataframe using a set of column conditions as keys? This seems to be a common need. Say you have a database of info and you need to pluck answers to questions from it, but you need one answer, not a series of possible answers. My method seems "hokey" -- not Pythonic? And maybe not good for technical reasons.
import pandas as pd
d = {'A': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'B': [1, 2, 3, 1, 2, 3, 1, 2, 3], 'C': [1, 3, 5,
2, 9, 7, 4, 3, 2]}
df = pd.DataFrame(data=d)
df looks like:
A B C
0 1 1 1
1 1 2 3
2 1 3 5
3 2 1 2
4 2 2 9
5 2 3 7
6 3 1 4
7 3 2 3
8 3 3 2
How to get the value in the C column where A == 1 and B == 3? In my case it's always unique, but I can see how that cannot be assumed so this method returns a series:
df[(df['A'] == 1) & (df['B'] == 3)]['C']
I don't want a series. So how to get a single value, not a series or list of one row or one element?
My method:
df[(df['A'] == 1) & (df['B'] == 3)]['C'].tolist()[0]
In the Pandas library it seems DataFrame.at is the way to go, but this method doesn't look better, though I wonder if it is technically better:
df.at[df.loc[(df['A'] == 1) & (df['B'] == 3)].index[0], 'C']
So, in your opinion, what is the best way to using multiple column conditions to find a value in a dataframe and return a single value (not a list or series)?