numpy中布尔掩码的逆向效应

时间:2016-05-04 21:59:31

标签: python numpy mask

设置

emails = ["email@example.com", "email@bad_domain", "email2@example.com", ...]
verified_domains = set()
for email in emails:
    domain = email.split("@")[-1]
    domain_verified = domain in verified_domains
    is_valid = validate_email(email, check_mx=not domain_verified)
    if is_valid:
        verified_domains.add(domain)

我可以像这样掩饰x:

np.random.seed(314)
x = np.random.rand(10, 4)
mask np.array([True, False, False, True])

x

array([[ 0.91687358,  0.58854191,  0.26504775,  0.78320538],
       [ 0.91800106,  0.82735501,  0.72795148,  0.26048042],
       [ 0.9117634 ,  0.26075656,  0.76637602,  0.26153114],
       [ 0.12229137,  0.38600554,  0.84008124,  0.27817936],
       [ 0.06991369,  0.63310965,  0.58476603,  0.58123194],
       [ 0.6772054 ,  0.6871551 ,  0.43892737,  0.3209265 ],
       [ 0.57055222,  0.47984862,  0.86107434,  0.83480474],
       [ 0.10576611,  0.06040804,  0.59688219,  0.79239497],
       [ 0.22635574,  0.5352008 ,  0.13606616,  0.37224445],
       [ 0.15197674,  0.42982185,  0.79270622,  0.40695651]])

问题

给定y = x[:, mask] y array([[ 0.91687358, 0.78320538], [ 0.91800106, 0.26048042], [ 0.9117634 , 0.26153114], [ 0.12229137, 0.27817936], [ 0.06991369, 0.58123194], [ 0.6772054 , 0.3209265 ], [ 0.57055222, 0.83480474], [ 0.10576611, 0.79239497], [ 0.22635574, 0.37224445], [ 0.15197674, 0.40695651]]) y如何生成:

mask

1 个答案:

答案 0 :(得分:1)

解决方案

z = np.zeros((y.shape[0], len(mask)))
z[:, mask] = y

z

array([[ 0.91687358,  0.        ,  0.        ,  0.78320538],
       [ 0.91800106,  0.        ,  0.        ,  0.26048042],
       [ 0.9117634 ,  0.        ,  0.        ,  0.26153114],
       [ 0.12229137,  0.        ,  0.        ,  0.27817936],
       [ 0.06991369,  0.        ,  0.        ,  0.58123194],
       [ 0.6772054 ,  0.        ,  0.        ,  0.3209265 ],
       [ 0.57055222,  0.        ,  0.        ,  0.83480474],
       [ 0.10576611,  0.        ,  0.        ,  0.79239497],
       [ 0.22635574,  0.        ,  0.        ,  0.37224445],
       [ 0.15197674,  0.        ,  0.        ,  0.40695651]])