gpt4 book ai didi

python - numpy - 使用 numpy 一维数组的置换副本构建二维数组的最快方法

转载 作者:行者123 更新时间:2023-11-28 20:44:06 25 4
gpt4 key购买 nike

>>> import numpy as np
>>> a = np.arange(5)
>>> b = desired_function(a, 4)
array([[0, 3, 4, 1],
... [1, 2, 1, 3],
... [2, 4, 2, 4],
... [3, 1, 3, 0],
... [4, 0, 0, 2]])

到目前为止我尝试了什么

def repeat_and_shuffle(a, ncols):
nrows, = a.shape
m = np.tile(a.reshape(nrows, 1), (1, ncols))
return m

我必须以某种方式有效地按列随机播放 m[:,1:ncols]

最佳答案

这是创建这样一个数组的一种方法:

>>> a = np.arange(5)
>>> perms = np.argsort(np.random.rand(a.shape[0], 3), axis=0) # 3 columns
>>> np.hstack((a[:,np.newaxis], a[perms]))
array([[0, 3, 1, 4],
[1, 2, 3, 0],
[2, 1, 4, 1],
[3, 4, 0, 3],
[4, 0, 2, 2]])

这将创建一个所需形状的随机值数组,然后按对应值对每列中的索引进行排序。这个索引数组然后用于索引 a

(使用 np.argsort 创建置换索引列数组的想法来自@jme 的回答 here。)

关于python - numpy - 使用 numpy 一维数组的置换副本构建二维数组的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27732111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com