本文介绍了使用其他系列过滤 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Pandas系列,我们将其称为roved_fields,我想使用它通过以下方式过滤df:

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

应用核准的字段过滤器后,生成的df应如下所示:

After applying the approved_field filter, the resulting df should look like:

    Field
0   Field1
1   Field2
2   Field2

谢谢!

推荐答案

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

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

这篇关于使用其他系列过滤 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 02:02