if else 语句基于 numpy 中带有矢量化函数的二进制数组



我有两个numpy数组:一个有二进制变量T = [0,1,1,0,0,...]另一个有一些随机值:X = [0.1, 0.2, 0.333...]。我想写一个函数,当T[i]等于0X[i] = 1 - X[i].我想知道是否有任何我可以依赖的矢量化功能,而不仅仅是循环两个数组for

尝试numpy.where

np.where(T == 0, 1 - X, X)

完整示例:

# import module
import numpy as np
# Create T vector (random)
T = np.random.randint(0, 2, 20)
print(T)
# [0 0 1 0 1 1 0 0 1 0 1 1 1 0 1 0 0 0 0 0]
# Create X vector (random)
X = np.random.random(20)
print(X)
# [0.60692623 0.4590666  0.25077907 0.39528167 0.31926095 0.97515345
#  0.00333958 0.24427309 0.4564238  0.22598126 0.52635721 0.04825686
#  0.88188174 0.11187227 0.93212834 0.63503694 0.52799418 0.07250929
#  0.45056039 0.22862652]
# Apply condition
X = np.where(T == 0, 1 - X, X)
print(X)
# [0.39307377 0.5409334  0.25077907 0.60471833 0.31926095 0.97515345
#  0.99666042 0.75572691 0.4564238  0.77401874 0.52635721 0.04825686
#  0.88188174 0.88812773 0.93212834 0.36496306 0.47200582 0.92749071
#  0.54943961 0.77137348]

注意:此解决方案假定TX具有相同的尺寸

相关内容

  • 没有找到相关文章