numpy~运算符和Boolean类型变量

  • numpy中取反运算符~可以将Boolean类型值取反,这在使用boolean类型数组选择数组中固定元素时十分有用。
import numpy as np
a=np.array([0,0,1,1]).astype("bool")
b=np.arange(4)
print("b\n",b)
# b
#  [0 1 2 3]
c=b[a]
print("c\n",c)
# c
#  [2 3]
print("~a\n",~a)
# ~a
#  [ True  True False False]
c_=b[~a]
print("c_\n",c_)
# c_
#  [0 1]

numpy中的0-1表示和Boolean类型具有一致性

loser_winner = np.array([1, 0, 0, 1, 0, 1])
if [0, 0, 1] == [False, False, True]:
    print("1")
else:
    print("0")
# 1
print(~loser_winner.astype(np.bool))
# [ True False False False  True False]
mutation_idx = [True, True, True, False, False, False]
loser_winner[mutation_idx] = ~loser_winner[mutation_idx].astype(np.bool)
print("loser_winner", loser_winner, "loser_winner[mutation_idx]", loser_winner[mutation_idx])
# loser_winner [0 1 1 1 0 1] loser_winner[mutation_idx] [0 1 1]