这是在其他论坛上提出的,但重点是nan。
我有一个简单的数据文件:
y=[[1,2,3,4,1],[1,2,0,4,5]]
df = pd.DataFrame(y)我很难理解任何和所有的工作方式。根据熊猫的文档' any‘返回"...whether any元素在请求的轴上是真实的“。
如果我用:
~(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根据我的理解,第二个命令的意思是:如果在请求的轴上任何元素都是True,那么返回' True‘,并且它应该为两行返回True,True (因为这两个行都包含至少一个真值),但是相反,我得到true,False。为什么会这样呢?
发布于 2017-12-16 19:05:18
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。
发布于 2017-12-16 19:03:35
您需要一个(),因为操作符的优先级:
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: boolhttps://stackoverflow.com/questions/47849011
复制相似问题