Home > database >  How to query Pandas df based on row values and column header with Python
How to query Pandas df based on row values and column header with Python

Time:07-12

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

CodePudding user response:

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


CodePudding user response:

You can get values of 'Value' to with this code

pd.read_csv(PATH)
data = data.dropna()
Value = data['Value'].values # Get values of 'Value'
# Key2 = data['Key2'].values # Get values of 'Key2'
print(Value)

And output will be

[55, 97]

CodePudding user response:

I think you just need this if key1 and key2 are in the index as a multiindex.

df.loc[('Disney', 'World'), 'Value']

CodePudding user response:

Just issue a multi-index expression on the series directly:

df.Value['Disney', 'World']
  • Related