问题描述
我有一个相对稀疏的数组,我想遍历每一行并仅对非零元素进行混洗.
示例输入:
[2,3,1,0][0,0,2,1]
示例输出:
[2,1,3,0][0,0,1,2]
注意零没有改变位置.
要打乱每行中的所有元素(包括零),我可以这样做:
for i in range(len(X)):np.random.shuffle(X[i, :])
当时我试图做的是:
for i in range(len(X)):np.random.shuffle(X[i, np.nonzero(X[i, :])])
但是没有效果.我注意到 X[i, np.nonzero(X[i, :])]
的返回类型与 X[i, :]
不同,这可能成为原因.
In[30]: X[i, np.nonzero(X[i, :])]出[30]:数组([[23, 5, 29, 11, 17]])在[31]: X[i, :]出[31]:数组([23, 5, 29, 11, 17])
您可以使用非就地 numpy.random.permutation
显式非零索引:
I have a an array that is relatively sparse, and I would like to go through each row and shuffle only the non-zero elements.
Example Input:
[2,3,1,0]
[0,0,2,1]
Example Output:
[2,1,3,0]
[0,0,1,2]
Note how the zeros have not changed position.
To shuffle all elements in each row (including zeros) I can do this:
for i in range(len(X)):
np.random.shuffle(X[i, :])
What I tried to do then is this:
for i in range(len(X)):
np.random.shuffle(X[i, np.nonzero(X[i, :])])
But it has no effect. I've noticed that the return type of X[i, np.nonzero(X[i, :])]
is different from X[i, :]
which might be thecause.
In[30]: X[i, np.nonzero(X[i, :])]
Out[30]: array([[23, 5, 29, 11, 17]])
In[31]: X[i, :]
Out[31]: array([23, 5, 29, 11, 17])
You could use the non-inplace numpy.random.permutation
with explicit non-zero indexing:
>>> X = np.array([[2,3,1,0], [0,0,2,1]])
>>> for i in range(len(X)):
... idx = np.nonzero(X[i])
... X[i][idx] = np.random.permutation(X[i][idx])
...
>>> X
array([[3, 2, 1, 0],
[0, 0, 2, 1]])
这篇关于混洗数组中每一行的非零元素 - Python/NumPy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!