【问题标题】:Efficiently permute array in row wise using Numpy使用 Numpy 有效地按行排列数组
【发布时间】:2021-11-21 12:40:30
【问题描述】:

给定一个二维数组,我想按行排列这个数组。

目前,我将创建一个 for 循环来逐行排列二维数组,如下所示:

for i in range(npart):
    pr=np.random.permutation(range(m))
    # arr_rand3 is the same as arr, but with each row permuted
    arr_rand3[i,:]=arr[i,pr]

但是,我想知道Numpy 中是否有一些设置可以在单行中执行此操作(没有 for 循环)。

完整代码是

import numpy as np

arr=np.array([[0,0,0,0,0],[0,4,1,1,1],[0,1,1,2,2],[0,3,2,2,2]])
npart=len(arr[:,0])
m=len(arr[0,:])
# Permuted version of arr
arr_rand3=np.zeros(shape=np.shape(arr),dtype=np.int)
# Nodal association matrix for C
X=np.zeros(shape=(m,m),dtype=np.double)
# Random nodal association matrix for C_rand3
X_rand3=np.zeros(shape=(m,m),dtype=np.double)
  
for i in range(npart):
    pr=np.random.permutation(range(m))
    # arr_rand3 is the same as arr, but with each row permuted
    arr_rand3[i,:]=arr[i,pr]

【问题讨论】:

  • 你用的是什么 numpy 版本?
  • 感谢您对此 OP 感兴趣,我正在使用 numpy==1.19.5

标签: python performance numpy


【解决方案1】:

在 Numpy 1.19+ 中你应该能够做到:

import numpy as np

arr = np.array([[0, 0, 0, 0, 0], [0, 4, 1, 1, 1], [0, 1, 1, 2, 2], [0, 3, 2, 2, 2]])

rng = np.random.default_rng()
arr_rand3 = rng.permutation(arr, axis=1)

print(arr_rand3)

输出

[[0 0 0 0 0]
 [4 0 1 1 1]
 [1 0 1 2 2]
 [3 0 2 2 2]]

根据documentation,方法random.Generator.permutation接收到一个新参数axis

轴整数,可选
x 被打乱的轴。默认为 0。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 2019-10-25
    • 2015-02-18
    相关资源
    最近更新 更多