【发布时间】:2025-12-14 04:05:01
【问题描述】:
给定一个 N rows by M columns 数组,我需要按 columns 对其进行洗牌,同时更新一个单独的(唯一)列索引列表以指向新的洗牌元素的位置。
例如取下面的(3, 5)数组
a = [[ 0.15337424 0.21176979 0.19846229 0.5245618 0.24452392]
[ 0.17460481 0.45727362 0.26914808 0.81620202 0.8898504 ]
[ 0.50104826 0.22457154 0.24044079 0.09524352 0.95904348]]
以及列索引列表:
idxs = [0 3 4]
如果我按列对数组进行洗牌,它看起来像这样:
a = [[ 0.24452392 0.19846229 0.5245618 0.21176979 0.15337424]
[ 0.8898504 0.26914808 0.81620202 0.45727362 0.17460481]
[ 0.95904348 0.24044079 0.09524352 0.22457154 0.50104826]]
索引数组应该修改成如下所示:
idxs = [4 2 0]
我可以通过在洗牌之前和之后转置它来按列对数组进行洗牌(参见下面的代码),但我不确定如何更新索引列表。整个过程需要尽可能快,因为它将使用新数组执行数百万次。
import numpy as np
def getData():
# Array of (N, M) dimensions
N, M = 10, 500
a = np.random.random((N, M))
# List of unique column indexes in a.
# This list could be empty, or it could have a length of 'M'
# (ie: contain all the indexes in the range of 'a').
P = int(M * np.random.uniform())
idxs = np.arange(0, M)
np.random.shuffle(idxs)
idxs = idxs[:P]
return a, idxs
a, idxs = getData()
# Shuffle a by columns
b = a.T
np.random.shuffle(b)
a = b.T
# Update the 'idxs' list?
【问题讨论】:
标签: python arrays performance numpy random