仅将 numpy.array 值替换为从数组中其他行中随机选择的值

问题描述 投票:0回答:2

我有以下形状数组 (A, B),其中 A=4 且 B=2:

[[1 1] [2 2] [3 3] [4 4]]
我想修改数组,使每一行都由其他行中随机选择的值组成,同一行内不重复。结果示例如下:
[[3 2] [1 3] [2 4] [3 1]]

我尝试使用 np.random.shuffle 和 np.random.choice 但我不知道如何排除行本身以及如何替换每个值而不是每行的值。 np.random.shuffle 导致:

[[4 4]    [2 2]    [3 3]    [1 1]]
并且 np.random.choice 给了我错误,因为我的数组是 2D 而不是 1D
我是初学者,我觉得这应该是显而易见的,但我一整天都在绞尽脑汁......任何帮助将非常感激

python numpy random numpy-ndarray
2个回答
0
投票

分别将

np.random.shuffle
应用于每一列

a = np.array([[1,1],[2,2],[3,3],[4,4]])
for col in range(a.shape[1]):
    np.random.shuffle(a[:,col])
print(a)

生成

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

0
投票

假设

A=N
矩阵的值始终为值 1 到 N,下面将生成一个随机矩阵,其中值来自该集合,但没有行包含该行的基于 1 的索引。

import random
N = 4
nums = list(range(1, N+1))
a = []
for irow in range(1, N+1):
    nums.remove(irow)
    a.append([random.choice(nums), random.choice(nums)])
    nums.append(irow)
print(a)

生成

[[3, 4], [4, 4], [4, 1], [1, 2]]

如果您想确保每列包含所有可能的值,但同样没有值出现在该行中且该值等于其从一开始的索引。以下应该可以解决问题

import random

def generate_all_moved_permutation_tree(level, nums):
    if len(nums) == 0:
        raise RunTimeError('generate_permutation_tree must be called with a non-empty nums list')
    if len(nums) == 1:
        if level == nums[0]:
            return None
        else:
            return {nums[0]: {}}
    allowed_nums = list(nums)
    if level in allowed_nums:
        allowed_nums.remove(level)
    result = {}
    for n in allowed_nums:
        sublevel_nums = list(nums)
        if n in sublevel_nums:
            sublevel_nums.remove(n)
        subtree = generate_all_moved_permutation_tree(level+1, sublevel_nums)
        if subtree is not None:
            result[n] = subtree
    if len(result) == 0:
        return None
    return result

def pick_an_all_moved_permutation(all_moved_permutation_tree):
    n = random.choice(list(all_moved_permutation_tree))
    l = [n]
    sub_tree = all_moved_permutation_tree[n]
    if len(sub_tree) > 0:
        l.extend(pick_an_all_moved_permutation(sub_tree))
    return l

示例

>>> t = generate_all_moved_permutation_tree(1, range(1,4))
{2: {3: {1: {}}}, 3: {1: {2: {}}}}
>>> print(list(zip(pick_an_all_moved_permutation(t), pick_an_all_moved_permutation(t))))
[(2, 4), (3, 1), (4, 2), (1, 3)]
>>> print(list(zip(pick_an_all_moved_permutation(t), pick_an_all_moved_permutation(t))))
[(3, 4), (1, 1), (4, 2), (2, 3)]
>>> print(list(zip(pick_an_all_moved_permutation(t), pick_an_all_moved_permutation(t))))
[(3, 2), (4, 1), (1, 4), (2, 3)]
© www.soinside.com 2019 - 2024. All rights reserved.