2

I want to construct a condition for my dataframe in a function by iterating through the given dictionary dict.

def get_condition(dataframe, dict={'col1':val1, 'col2':val2, 'col3':val3})":

     condition = ...          

     return condition  

Expected output

condition = (dataframe['col1']==val1) & (dataframe['col2']==val2) & (dataframe['col3']==val3)

How to do this?

4
  • Do you want to build a string, or to actually execute and resolve this condition ? Commented Jul 26, 2018 at 13:37
  • At the end I want to have a dataframe_new = dataframe[condition] . But I want construct this condition first iteratively using a function. Commented Jul 26, 2018 at 13:41
  • I think stroring the strings and then using eval() would work, if I understood what you want ? But it sounds like a code smell ? Commented Jul 26, 2018 at 13:43
  • 1
    See answer. In reference to your original code, beware of mutable default arguments. Also, by using dict as the variable name for your dictionary, you're overwriting the builtin dict type/function, which should generally be avoided if possible. Commented Jul 26, 2018 at 13:56

2 Answers 2

3
def get_condition(df, d):
    d = list(d.items())

    first_col, first_val = d[0]
    cond = df[first_col] == first_val
    for col, val in d[1:]:
        cond &= df[col] == val

    return cond
Sign up to request clarification or add additional context in comments.

Comments

2

Not sure, if you want to create a boolean filter.

def get_condition(dataframe, dictionary):
    # create series with all values set to true
    condition = pd.Series([True] * len(dataframe))

    for k, v in dictionary.items():
        condition &= dataframe[k] == v
    return condition  

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.