Python 有选择性条件的Numpy洗牌?

Python 有选择性条件的Numpy洗牌?,python,arrays,numpy,Python,Arrays,Numpy,我想用一个条件洗牌一个2d Numpy数组。例如,仅洗牌非零值 将numpy导入为np a=np.arange(9)。重塑((3,3)) a[2,2]=0 #洗牌非零值 #仅0停留在原地的示例洗牌 >>>a 数组([[0,5,3], [7, 2, 6], [4, 1, 0]]) 您可以执行以下操作: 将numpy导入为np a=np.arange(9)。重塑((3,3)) a[2,2]=0 c=a[a!=0] np.random.shuffle(c) a[a!=0]=c A. #数组([[0,6

我想用一个条件洗牌一个2d Numpy数组。例如,仅洗牌非零值

将numpy导入为np
a=np.arange(9)。重塑((3,3))
a[2,2]=0
#洗牌非零值
#仅0停留在原地的示例洗牌
>>>a
数组([[0,5,3],
[7, 2, 6],
[4, 1, 0]])
您可以执行以下操作:

将numpy导入为np
a=np.arange(9)。重塑((3,3))
a[2,2]=0
c=a[a!=0]
np.random.shuffle(c)
a[a!=0]=c
A.
#数组([[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
更简洁的方法是:

a=np.arange(9).重塑((3,3))
a[2,2]=0
a[a>3]=np.随机排列(a[a>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)
与:


例如,要仅对偶数进行无序排列,您可以使用
b%2==0
作为
条件

初始数组和无序排列的数组是否应具有相同的元素?是–对所有值进行无序排列,但不包括满足条件的值。检查@Brella对我的答案的评论,您应该接受另一个答案,我没有考虑到一个错误
idx, = np.where(condition)