I have a pandas df:
and want to iterate though a dictionary of filters to isolate the desired row.
For example, filtering on the following should return row:
df = pd.DataFrame([[10,'A','40%'],
[20,'B','20%'],
[30,'C','10%'],
[40,'D','30%']],
columns= ['Col1','Col2','%'])
dic = {'Col1': 10, 'Col2': 'A'}
My current approach is hardcoded to accept just two filter conditions (Col1, Col2) however I need a more generalized approach that can accept N conditions (or a dict of any size).
CodePudding user response:
You can use a Series for automatic alignment and any
or all
depending on whether you want any or all conditions True:
dic = {'Col1': 10, 'Col2': 'A'}
# we want both Col1 AND Col2 to match
out = df[df[list(dic)].eq(pd.Series(dic)).all(1)]
# we want either Col1 OR Col2 to match (or both)
out = df[df[list(dic)].eq(pd.Series(dic)).any(1)]
output:
Col1 Col2 %
0 10 A 40%
CodePudding user response:
I can't load your pictures but what about this approach?
conditions_dict = {'Col1': 10, 'Col2': 'A'}
def filter_function(row):
for col, val in conditions_dict.items():
if row[col] != val:
return False
return True
df[df.apply(filter_function, axis=1)]
CodePudding user response:
You can try create DataFrame from dict then merge
out = pd.DataFrame([dic]).merge(df)
print(out)
Col1 Col2 %
0 10 A 40%