简体   繁体   中英

how can i swap list in a matrix in python?

I want to shuffle 3D matrix's rows but it doesn't work in a matrix here is some example code

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)

in this code I want to shuffle data from some row list to another row list

but it's result doesn't work swaping but overwriting

here is result

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

how can i swap list in matrix?

thanks

import numpy as np

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, target]] = data[[target, 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)

If you want to shuffle along the first axis, just use 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)

Output:

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

If you want to shuffle along any other axis in data , you can shuffle the array view returned by np.swapaxes . For example, to shuffle the rows of the inner 2D matrices, do:

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

Output:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM