使用另一个系列过滤Pandas数据帧

时间:2013-06-11 14:37:49

标签: python python-2.7 pandas

我有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

谢谢!

2 个答案:

答案 0 :(得分:7)

您可以使用isin和布尔索引:

>>> 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

答案 1 :(得分: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