Skip to content Skip to sidebar Skip to footer

Filter Data Iteratively In Python Data Frame

I'm wondering about existing pandas functionalities, that I might not been able to find so far. Bascially, I have a data frame with various columns. I'd like to select specific row

Solution 1:

You could use query() method to filter data, and construct filter expression from parameters like

In[288]: df.query(' and '.join(['{0}=={1}'.format(x[0], x[1]) for x in parameter]))
Out[288]:
   ABCD1125b

Details

In [296]: df
Out[296]:
   A  B  C  D
0124  a
1125  b
2134  c

In [297]: query =' and '.join(['{0}=={1}'.format(x[0], x[1]) for x inparameter])

In [298]: query
Out[298]: 'A==1 and B==2 and C==5'In [299]: df.query(query)
Out[299]:
   A  B  C  D
1125  b

Solution 2:

Just for the information if others are interested, I would have done it this way:

import numpy as np
matched = np.all([df[vn] == vv for vn, vv in parameters], axis=0)
df_filtered = df[matched]

But I like the query function better, now that I have seen it @John Galt.

Post a Comment for "Filter Data Iteratively In Python Data Frame"