一个例子可以直截了当地说明:
import numpy
# ------------------------------------------------------------------------
# Edit:
# commenting out below `a` assignation for the more general case as shown
#+below this commented block
# ------------------------------------------------------------------------
# a = np.array(range(8))
# print a
# array([0, 1, 2, 3, 4, 5, 6, 7])
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
a = np.random.randn(8)
print a
array([-0.53683985, -0.321736 , 0.15684836, 0.32085469, 1.99615701,
-1.16908367, -0.10995894, -1.90925978])
b = [4, 7]
# ^ ^ These values are indices of values in `a` I want to keep unchanged
# I want to set all values to,
# say np.random.random_integers(10, 100) or simply `nan` except for indices given by `b`:
# So I want something like this:
a[: (!b)] = np.random.random_integers(10, 100) # I'm using "!" as the NOT operator
print a
array([62, 96, 47, 74, 1.99615701, 32, 11, -1.90925978])
# not changed: ^^^^^^^^^^ ^^^^^^^^^^
# or:
a[: (!b)] = np.nan
print a
array([nan, nan, nan, nan, 1.99615701, nan, nan, -1.90925978])
# not changed: ^^^^^^^^^^ ^^^^^^^^^^
我知道我可以使用 np.ma.array(a, mask = False) 和 a.mask[b] = True,但是从这一点开始,我不知道如何将我的随机数分配给仅未屏蔽的值