numpy取反操作符和Boolean類型


numpy~運算符和Boolean類型變量

覺得有用的話,歡迎一起討論相互學習~

我的微博我的github我的B站

  • 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]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM