Reputation: 41
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?
Upvotes: 2
Views: 629
Reputation: 703
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
Upvotes: 2
Reputation: 2945
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
Upvotes: 3