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

pb3skfrl  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(93)

我有一个形状为(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
我是一个初学者,我觉得这应该是显而易见的,但我一直在绞尽脑汁一整天…任何帮助将非常感谢

gc0ot86w

gc0ot86w1#

假设A=N矩阵的值总是从1到N,下面将生成一个随机矩阵,其中的值来自该集合,但没有一行包含该行的索引。

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))
>>> print(t)
{2: {3: {1: {}}}, 3: {1: {2: {}}}}
>>> t = generate_all_moved_permutation_tree(1, range(1,5))
>>> 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)]

bqf10yzr

bqf10yzr2#

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]]

相关问题