I want to get a single value from a pandas DataFrame more efficiently.
This is how I do it now:
# import pandas
import pandas as pd
# set up the dataframe
df = pd.DataFrame({'col1':['a','a','b'],'col2':[10,20,20],'col3':[100.0,200.0,300.0]})
# STEP 1 - filter down to a single row with loc
row_of_interest = df.loc[(df['col1'] == 'a') & (df['col2'] > 11)]
# STEP 2 - specify the column of interest
column_and_row_of_interest = row_of_interest['col3']
# STEP 3 - get the value out of dataframe format using to_list and list indexing
value_of_interest = column_and_row_of_interest.to_list()[0]
And of course, I can do steps 1-3 in a single line of code like this:
value_of_interest = df.loc[(df['col1'] == 'a') & (df['col2'] > 11)]['col3'].to_list()[0]
I imagine STEP 1 and STEP 2 might be unavoidable, but STEP 3 feels clunky. Is there a better way to get a value out of a DataFrame with a shape of (1,1) than using .to_list()[0] ?
>Solution :
You can do:
print(column_and_row_of_interest.squeeze())
OR:
print(column_and_row_of_interest.iat[0])
This prints:
200.0