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

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -