Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How could I get a value out of a pandas DataFrame with a shape of (1,1) without using .to_list()[0]?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading