LoginSignup
0
0

More than 1 year has passed since last update.

Pandas: データフレームについて--08: 論理演算

Last updated at Posted at 2022-06-21

論理演算 allany と 排他論理和

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

数値の場合,
00.0False,それ以外なら True

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

文字列の場合,空文字列 ''False,それ以外なら 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

論理値 True/False だけを含む行や列を対象にするときは,bool_only=True を指定する。

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. TrueFalse の反転

論理値の場合,FalseTrueTrueFalse に反転する。

数値の場合, 0 を 1,1 を 0 に反転する。0,1 以外の数値は 2 進数表記のビットの 1 との 排他論理和したものを数値として読んだときの値1になる。

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 になる。

0
0
0

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
  3. You can use dark theme
What you can do with signing up
0
0