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 to query Pandas df based on row values and column header with Python

Is there a way to query the df based on the row values and column header? Looking to pass through Disney, World, and Value as variables to return 55. I tried using the df.loc function but received errors. The Key1 and Key2 headers are set as the df.index.

Pandas Dataframe

Key1 Key2 Value
Disney World 55
Disney Land 97

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

>Solution :

IIUC, you create a function, pass the parameters and get the value in return

def findval(df, Key1, Key2):
    return df[(df['Key1'] == Key1) & 
              (df['Key2'] == Key2)]['Value']

findval(df, 'Disney', 'Land')

1 97
Name: Value, dtype: int64


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