Skip to content Skip to sidebar Skip to footer

Filter Pandas Dataframe With Another Series

I have Pandas Series we'll call approved_fields which I'd like to use to filter a df by: approved_field(['Field1','Field2','Field3')] df Field 0 Field1 1 Field4 2 Field2

Solution 1:

You can use isin and boolean indexing:

>>> import pandas as pd
>>> df = pd.DataFrame({"Field": "Field1 Field4 Field2 Field5 Field2".split()})
>>> approved_fields = "Field1", "Field2", "Field3"
>>> df['Field'].isin(approved_fields)
0     True
1    False
2     True
3    False
4     True
Name: Field, dtype: bool
>>> df[df['Field'].isin(approved_fields)]
    Field
0  Field1
2  Field2
4  Field2

Solution 2:

Note that you indices in your expected solution are off

In [16]: approved_field = ['Field1','Field2','Field3']

In [17]: df = DataFrame(dict(Field = ['Field1','Field4','Field2','Field5','Field2']))

In [18]: df
Out[18]: 
    Field
0  Field1
1  Field4
2  Field2
3  Field5
4  Field2

In [19]: df[df.Field.isin(approved_field)]
Out[19]: 
    Field
0  Field1
2  Field2
4  Field2

Post a Comment for "Filter Pandas Dataframe With Another Series"