脾气暴躁的选择条件?

时间:2019-07-15 14:41:14

标签: python arrays numpy

我想用条件对2d Numpy数组进行洗牌。例如,仅混洗非零值。

import numpy as np
a = np.arange(9).reshape((3,3))
a[2,2] = 0

# Shuffle non-zero values 

# Example shuffle with only 0 staying in place
>>> a
array([[0, 5, 3],
       [7, 2, 6],
       [4, 1, 0]])

2 个答案:

答案 0 :(得分:4)

您可以做到:

import numpy as np
a = np.arange(9).reshape((3,3))
a[2,2] = 0
c = a[a!=0]
np.random.shuffle(c)
a[a!=0] = c
a 
> array([[0, 6, 5],
         [2, 3, 7],
         [4, 1, 0]])

如果您有其他状况,可以这样做:

import numpy as np
a = np.arange(9).reshape((3,3))
a[2,2] = 0
cond = a>3
c = a[cond]
np.random.shuffle(c)
a[cond] = c

答案 1 :(得分:3)

这是一种实现方法:

import numpy as np

np.random.seed(0)
a = np.arange(9).reshape((3,3))
a[2,2] = 0

# Take a flattened version of the array
b = a.flatten()  # If you do not need a copy use a.ravel()
# Find indices of non-zero values
idx, = np.nonzero(b)
# Shuffle those indices
b[idx] = b[np.random.permutation(idx)]
# Put back into original shape
b = b.reshape(a.shape)
print(b)
# [[0 7 3]
#  [2 4 1]
#  [6 5 0]]

如果要使用其他条件,只需替换:

idx, = np.nonzero(b)

使用:

idx, = np.where(condition)

例如,要只对偶数个数字进行随机播放,可以将b % 2 == 0用作condition