一个解决方案(以防您只想填充最后一个轴.如果要对所有轴执行此操作,则需要对所有轴重复此操作.)
def fillLastAxis(arr):
# Position in all but last axes of rows that need a 1
pos=~arr.any(axis=-1) # True on rows coords that miss a 1
# Number of 1 to generate
num=pos.sum()
# Index (along the last axis, of the missing 1)
idx=np.random.randint(0, arr.shape[-1], num)
# Just add a one at this pos
arr[pos, idx]=1
测试:
size = (3, 5, 5)
proba_0 = 0.7
n_positions = np.random.choice([0,1], size=size, p=[proba_0, 1-proba_0])
print("==== Before ====")
print(n_positions)
fillLastAxis(n_positions)
print("==== After ====")
print(n_positions)
展示会
==== Before ====
[[[1 0 1 1 1]
[1 0 0 0 1]
[0 1 0 0 0]
[0 0 0 0 0]
[1 0 1 0 1]]
[[0 0 1 0 1]
[0 0 0 0 0]
[0 0 0 0 1]
[0 1 1 0 1]
[0 0 0 0 0]]
[[0 0 0 0 1]
[0 0 0 1 1]
[1 1 1 0 1]
[0 1 0 0 0]
[0 1 0 0 1]]]
==== After ====
[[[1 0 1 1 1]
[1 0 0 0 1]
[0 1 0 0 0]
[0 1 0 0 0]
[1 0 1 0 1]]
[[0 0 1 0 1]
[0 0 1 0 0]
[0 0 0 0 1]
[0 1 1 0 1]
[0 0 0 1 0]]
[[0 0 0 0 1]
[0 0 0 1 1]
[1 1 1 0 1]
[0 1 0 0 0]
[0 1 0 0 1]]]
您可以看到,平面0的第3行和平面1的第1行之前缺少1.并在之后有一个(在位置1和2).
用更高的维度(用更多的轴进行测试,并减少这只是运气的可能性).这一次我强制种子,这样你就可以在家里测试,并判断结果,而不需要我打印整个数组,因为你有相同的.
size = (3, 6, 4, 5)
proba_0 = 0.5
np.random.seed(12)
n_positions = np.random.choice([0,1], size=size, p=[proba_0, 1-proba_0])
print("==== Before ====")
print(n_positions)
fillLastAxis(n_positions)
print("==== After ====")
print(n_positions)
如果我是正确的,那么结果中有3行全为0([0,2,1,:]
、[2,0,3,:]
和[2,4,3,:]
).它们都填满了一个随机的1之后.