【问题标题】:inconsistent any vs all pd dataframe任何与所有 pd 数据帧不一致
【发布时间】:2017-12-17 03:05:18
【问题描述】:

这是在其他论坛上提出的,但重点是 nan。

我有一个简单的数据框:

 y=[[1,2,3,4,1],[1,2,0,4,5]]
 df = pd.DataFrame(y)

我很难理解 any 和 all 的工作原理。根据 pandas 文档,“任何”返回“......任何元素在请求的轴上是否为真”。

如果我使用:

~(df == 0)
Out[77]: 
    0     1      2     3     4
0  True  True   True  True  True
1  True  True  False  True  True


~(df == 0).any(1)
Out[78]: 
0     True
1    False
dtype: bool

根据我的理解,第二个命令的意思是:如果任何元素在请求的轴上为真,则返回“真”,并且它应该为两行返回真,真(因为两者都包含至少一个真值),但我得到的是真,错误的。这是为什么呢?

【问题讨论】:

标签: python pandas any


【解决方案1】:

您需要一个(),因为运营商的优先级:

print (df == 0)
       0      1      2      3      4
0  False  False  False  False  False
1  False  False   True  False  False

print (~(df == 0))
      0     1      2     3     4
0  True  True   True  True  True
1  True  True  False  True  True

print ((~(df == 0)).any(1))
0    True
1    True
dtype: bool

因为:

print ((df == 0).any(1))
0    False
1     True
dtype: bool

print (~(df == 0).any(1))
0     True
1    False
dtype: bool

【讨论】:

  • 哦,是的,这很有道理。非常感谢您的快速回答。
【解决方案2】:

Python 将您的调用解释为:

~ ( (df == 0).any(1) )

所以它**首先评估any。现在如果我们看一下df == 0,我们会看到:

>>> df == 0
       0      1      2      3      4
0  False  False  False  False  False
1  False  False   True  False  False

所以这意味着第一行没有True,第二行有,所以:

>>> (df == 0).any(1)
0    False
1     True
dtype: bool

现在我们用~ 否定这个,所以False 变成True,反之亦然:

>>> ~ (df == 0).any(1)
0     True
1    False
dtype: bool

如果我们先否定,我们会看到:

>>> (~ (df == 0)).any(1)
0    True
1    True
dtype: bool

两者都是True,因为在两行中至少有一列是True

【讨论】:

  • 完美,有道理。谢谢你的解释!!
  • 谢谢你们,Willem 和 jezrael,很好的解释!!
猜你喜欢
  • 2020-02-27
  • 2016-02-29
  • 2022-01-09
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 2020-06-24
  • 2019-04-01
  • 1970-01-01
相关资源
最近更新 更多