pandas - Python - Filter DataFrame by flexible length dict -
this question has answer here:
i got dataframe this:
b c 1 1 3 5 2 1 3 6 3 2 4 7 4 2 4 8
i know can filter fixed column below:
df[df[a]==1 & df[b]==3]
but if want filter dataframe flexible length of dict:
dict = {'a':1, 'b':3, 'c':5]}
or
dict = {'a':2, 'b':4}
and can get:
b c 1 1 3 5
or
b c 3 2 4 7 4 2 4 8
how can solve problem?
if dictionary has values in list can pass dataframe isin
method.
d = {'a':[1], 'b':[3], 'c':[5]} df[df.isin(d)[list(d.keys())].all(axis=1)] b c 1 1 3 5
if have lots of items in dictionary, can automate conversion of values 1 item lists this.
{k:[v] k,v in d.items()}
Comments
Post a Comment