如何在python矩阵中交换列表?

时间:2018-11-15 03:22:15

标签: python numpy swap

我想重新排列3D矩阵的行,但在矩阵中不起作用 这是一些示例代码

def shuffle(data,data_size):
    for step in range(int(1*data_size)):
        selected = int(np.random.uniform(0,data_size))
        target = int(np.random.uniform(0,data_size))   

        print(data)
        if selected!=target:
            data[selected], data[target] = data[target], data[selected]            

            print(selected," and ",target, " are changed")
    return data

data = [[[1,2,3,4],[1,2,3,5],[1,2,3,6]],
        [[2,2,3,4],[2,2,3,5],[2,2,3,6]],
        [[3,2,3,4],[3,2,3,5],[3,2,3,6]] ]

data = np.array(data)
data = shuffle(data,3)

在这段代码中,我想将数据从某个行列表拖曳到另一个行列表

但结果是交换不起作用,但会覆盖

这是结果

[[[1 2 3 4]
  [1 2 3 5]
  [1 2 3 6]]

 [[2 2 3 4]
  [2 2 3 5]
  [2 2 3 6]]

 [[3 2 3 4]
  [3 2 3 5]
  [3 2 3 6]]]
2  and  1  are changed
[[[1 2 3 4]
  [1 2 3 5]
  [1 2 3 6]]

 [[2 2 3 4]
  [2 2 3 5]
  [2 2 3 6]]

 [[2 2 3 4]
  [2 2 3 5]
  [2 2 3 6]]]
1  and  0  are changed
[[[1 2 3 4]
  [1 2 3 5]
  [1 2 3 6]]

 [[1 2 3 4]
  [1 2 3 5]
  [1 2 3 6]]

 [[2 2 3 4]
  [2 2 3 5]
  [2 2 3 6]]]
0  and  2  are changed
[[[2 2 3 4]
  [2 2 3 5]
  [2 2 3 6]]

 [[1 2 3 4]
  [1 2 3 5]
  [1 2 3 6]]

 [[2 2 3 4]
  [2 2 3 5]
  [2 2 3 6]]]
2  and  1  are changed

如何交换矩阵中的列表?

谢谢

2 个答案:

答案 0 :(得分:1)

mark-compact

答案 1 :(得分:1)

如果要沿第一个轴随机播放,只需使用INSERT INTO MyGuests (id, lastname) VALUES (2, 'Doe') ON DUPLICATE KEY UPDATE lastname = 'Doe'

np.random.shuffle

输出:

data = np.array([
    [[1,2,3,4],[1,2,3,5],[1,2,3,6]],
    [[2,2,3,4],[2,2,3,5],[2,2,3,6]],
    [[3,2,3,4],[3,2,3,5],[3,2,3,6]]
])

np.random.shuffle(data)
print(data)

如果要沿[[[3 2 3 4] [3 2 3 5] [3 2 3 6]] [[1 2 3 4] [1 2 3 5] [1 2 3 6]] [[2 2 3 4] [2 2 3 5] [2 2 3 6]]] 中的任何其他轴随机播放,可以随机播放data返回的数组视图。例如,要随机排列内部2D矩阵的行,请执行以下操作:

np.swapaxes

输出:

swap = np.swapaxes(data, 1, 0)
np.random.shuffle(swap)
print(data)