python - 通过内省(introspection)行的每个元素来过滤 pandas 数据框

标签 python pandas filtering series

我有一个数据框,其中包含列中的一个对象。

例如:

df['id_original'].iloc[0].Class
Out[20]: u'Classtype1'

df['id_original'].iloc[1].Class
Out[20]: u'Classtype2'

如何过滤数据帧,只获取“id_original”行包含属性 Class 为 Classtype1 的对象的行。或者甚至更好。与 .isin(allowed_class_type_list) 结合使用?

有什么方法可以使用 .isin 实现此目的,还是我必须使用 iterrows 迭代所有行?首选优雅的单线解决方案。

最佳答案

您可以使用:

df.loc[df['id_original'].apply(lambda x: x.Class in allowed_class_type_list)]

考虑下面的缩小示例:

class Example:
    def __init__(self, class_):
        self.Class = class_

ex1 = Example('class1')
ex2 = Example('class2')
ex3 = Example('class3')
ex4 = Example('class4')

df = pd.DataFrame({
    'id_original':[ex1, ex2, ex2, ex1, ex4, ex3, ex3, ex4]
})

allowed_class_type_list = ['class1', 'class4']

您可以使用以下方式进行过滤:

df.loc[df['id_original'].apply(lambda x: x.Class in allowed_class_type_list)]

输出:

                   id_original
0   <__main__.Example object at 0x000000000A597390>
3   <__main__.Example object at 0x000000000A597390>
4   <__main__.Example object at 0x000000000A597B00>
7   <__main__.Example object at 0x000000000A597B00>

关于python - 通过内省(introspection)行的每个元素来过滤 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50839884/

相关文章:

python - 从串行连接获取 b'\x0 8'b'\x9e'b'\x1d' 或 b'\xe 0'b'\xe 0'b' 错误

python - NameError:名称 'self' 未在 EXEC/EVAL 中定义

javascript - 如何在不使用 "linebreaksbr"模板过滤器的情况下在 Django 模板中显示换行符?

python - 规范错误: nested renamer is not supported error while using agg function on dictionary

python - 删除重复数据并将其余数据附加到 Pandas 中

kotlin - 使用 SearchView 过滤 RecyclerView/ListAdapter

php - 在数组中查找非重复元素

python - 通过 Flask 应用程序的 Cherrypy 调度获取正确的静态 URL

python - 有效地计算数据框中两行之间的差异

javascript - 使用自定义过滤器通过嵌套 ng-repeats 进行过滤