混洗数组中每一行的非零元素 - Python/NumPy [英] Shuffling non-zero elements of each row in an array - Python / NumPy

查看:29
本文介绍了混洗数组中每一行的非零元素 - Python/NumPy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相对稀疏的数组,我想遍历每一行并仅对非零元素进行混洗.

示例输入:

[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 显式非零索引:

<预><代码>>>>X = np.array([[2,3,1,0], [0,0,2,1]])>>>对于范围内的 i(len(X)):... idx = np.nonzero(X[i])... X[i][idx] = np.random.permutation(X[i][idx])...>>>X数组([[3, 2, 1, 0],[0, 0, 2, 1]])

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 the cause.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆