2

Right now, I select multiple rows where certain columns have a particular value this way:

df.loc[(df['col1'] == val1) & (df['col2'] == val2)]

Is there a way I can do this programmatically, I provide the column key/value as a dict? Something like this:

def get_df(cols)

   df.loc[ (df[k] == v) for k,v in cols.items() ]

But I'm not sure how to 'AND' the expressions. Any ideas?

1 Answer 1

4

You can create a Series from the dictionary and make the comparison:

import numpy as np
import pandas as pd
np.random.seed(0)

df = pd.DataFrame(np.random.randint(0, 5, (100, 3)), columns = list("ABC"))
cols = {"A": 0, "B": 3, "C": 3}

df[(df == pd.Series(cols)).all(axis=1)]
Out: 
    A  B  C
94  0  3  3

Or, use np.logical_and with reduce:

df[np.logical_and.reduce([(df[k] == v) for k,v in cols.items()])]

    A  B  C
94  0  3  3
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.