【问题标题】:Is there an equivalent of the python built in function `all` in pandas?熊猫中是否有相当于python内置函数“all”的功能?
【发布时间】:2017-03-29 21:16:03
【问题描述】:

我正在像这样查询熊猫数据框df

df = df[
    (df.value1 >= threshold1) &
    (df.value2 >= threshold2) &
    (df.value3.isin(list3))
    ]

Python 有内置函数all,它允许这种语法:

if all([
    value1 > threshold1,
    value2 > threshold2,
    value3 in list3,
    ]):

而不是这个:

if (
    value1 > threshold1 and
    value2 > threshold2 and
    value3 in list3,
    ):

Pandas 在 Python 中有类似于 all 的东西吗?谢谢。

另外,这是基于多个条件对 Pandas 数据框进行子集化的最快方法吗?

【问题讨论】:

  • 这真的不是all 的用例,通常我会用and 来写。
  • 那么all 的用例是什么?谢谢。
  • 类似all(condition(x) for x in some_iterable)
  • 请注意,您使用all 可以满足您的需求,但这不是惯用的。在我摸索它之前,我必须看几次代码。我会立即知道使用and 的行在做什么。此外,您对 all 的使用会创建不必要的中间数据结构,并使用函数调用。它效率不高,我不鼓励使用它,尤其是当您在循环中重复评估条件时。
  • 我明白了!确实,它反对the official style guide

标签: python pandas conditional-statements subset built-in


【解决方案1】:

@juanpa.arrivillaga 已经给你很好地解释了 Pandas 中的布尔索引。

我想给你一个更好的选择 - DataFrame.query() 方法:

df.query("value1 > @threshold1 and value2 > @threshold2 and value3 in @list3")

演示:

In [138]: df = pd.DataFrame(np.random.randint(1, 10, (10, 3)),
                            columns=['value1','value2','value3'])

In [139]: df
Out[139]:
   value1  value2  value3
0       7       9       1
1       4       1       3
2       3       8       8
3       2       8       9
4       9       2       7
5       5       8       9
6       4       2       9
7       7       2       5
8       6       3       5
9       9       1       5

In [140]: threshold1 = 2

In [141]: threshold2 = 4

In [142]: list3 = [1,9]

In [143]: df.query("value1 > @threshold1 and value2 > @threshold2 and value3 in @list3")
Out[143]:
   value1  value2  value3
0       7       9       1
5       5       8       9

【讨论】:

    猜你喜欢
    • 2020-03-22
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 2021-10-03
    • 2012-06-18
    • 2023-03-31
    相关资源
    最近更新 更多