7

我有 Pandas 系列,我们将其称为approved_fields,我想用它来过滤df:

approved_field(['Field1','Field2','Field3')]

df
    Field
0   Field1
1   Field4
2   Field2
3   Field5
4   Field2

应用approved_field 过滤器后,生成的df 应如下所示:

    Field
0   Field1
1   Field2
2   Field2

谢谢!

4

2 回答 2

16

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
于 2013-06-11T14:44:27.597 回答
3

请注意,您预期解决方案中的索引已关闭

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
于 2013-06-11T14:46:57.653 回答