0

posted at

updated at

# 論理演算 `all` と `any` と 排他論理和

``````import pandas as pd

df = pd.DataFrame({
'x': [1, 2, 3, 4, 5],
'y': [1, 0, 0, 0, 1],
'z': [0, 0, 0, 0, 1],
'b': [True, False, True, True, True]})
df
``````
x y z b
0 1 1 0 True
1 2 0 0 False
2 3 0 0 True
3 4 0 0 True
4 5 1 1 True

`0``0.0``False`，それ以外なら `True`

``````bool(0.0), bool(0), bool(1), bool(123)
``````
``````(False, False, True, True)
``````

``````bool(''), bool('False'), bool('123'), bool('0.0')
``````
``````(False, True, True, True)
``````

## 1.　すべてが `True` か?

`all` は，すべての要素が `True` であるときに `True`

``````all(axis=0, bool_only=None, skipna=True, level=None, **kwargs)
``````
``````df.all() # axis=0 列ごと
``````
``````x     True
y    False
z    False
b    False
dtype: bool
``````
``````df.all(axis=1) # 行ごと
``````
``````0    False
1    False
2    False
3    False
4     True
dtype: bool
``````

``````df.all(bool_only=True) # axis=0 列ごと
``````
``````b    False
dtype: bool
``````

## 2.　どれかが `True` か?

`any` は，どれか 1 つの要素でも `True` であるときに `True`

``````any(axis=0, bool_only=None, skipna=True, level=None, **kwargs)
``````
``````df.any() # axis=0 列ごと
``````
``````x    True
y    True
z    True
b    True
dtype: bool
``````
``````df.any(axis=1) # 行ごと
``````
``````0    True
1    True
2    True
3    True
4    True
dtype: bool
``````

## 3.　`True` と `False` の反転

``````negate = df^1
negate
``````
x y z b
0 0 0 1 False
1 3 1 1 True
2 2 1 1 False
3 5 1 1 False
4 4 0 0 False
``````negate.all()
``````
``````x    False
y    False
z    False
b    False
dtype: bool
``````
``````negate.all(axis=1)
``````
``````0    False
1     True
2    False
3    False
4    False
dtype: bool
``````
``````negate.any()
``````
``````x    True
y    True
z    True
b    True
dtype: bool
``````
``````negate.any(axis=1)
``````
``````0    True
1    True
2    True
3    True
4    True
dtype: bool
``````

## 4.　もっと知りたい人

``````help(df.all) # Help on method all in module pandas.core.generic
help(df.any) # Help on method any in module pandas.core.generic
``````
1. 例えば，　5 は 101(2) なので，001(2) との排他論理和をとると 100(2) = 4 になる。

Register as a new user and use Qiita more conveniently

1. You get articles that match your needs
2. You can efficiently read back useful information
What you can do with signing up
0