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
3 Field5
4 Field2
After applying the approved_field filter, the resulting df should look like:
Field
0 Field1
1 Field2
2 Field2
Thanks!
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.