改组 numpy 数组以保持各自的值
Shuffling numpy arrays keeping the respective values
我有两个 numpy 数组,都有 100 万个空格,第一个数组中的所有值都与第二个数组中的值对应。我想在保持各自价值的同时洗牌他们两个。我该怎么做?
由于两个数组的大小相同,您可以使用 Numpy Array Indexing.
def unison_shuffled_copies(a, b):
assert len(a) == len(b) # don't need if we know array a and b is same length
p = numpy.random.permutation(len(a)) # generate the shuffled indices
return a[p], b[p] # make the shuffled copies using same arrangement according to p
这是参考 this answer,有一些变化。
您可以通过 get_state() and reset it between shuffles with set_state() 跟踪 numpy.random.state
。这将使洗牌在两个数组上的行为相同。
import numpy as np
arr1 = np.arange(9).reshape((3, 3))
arr2 = np.arange(10,19).reshape((3, 3))
arr1, arr2
# array([[0, 1, 2],
# [3, 4, 5],
# [6, 7, 8]]),
# array([[10, 11, 12],
# [13, 14, 15],
# [16, 17, 18]])
# get state
state = np.random.get_state()
np.random.shuffle(arr1)
arr1
# array([[6, 7, 8],
# [3, 4, 5],
# [0, 1, 2]])
# reset state and shuffle other array
np.random.set_state(state)
np.random.shuffle(arr2)
arr2
#array([[16, 17, 18],
# [13, 14, 15],
# [10, 11, 12]])
我有两个 numpy 数组,都有 100 万个空格,第一个数组中的所有值都与第二个数组中的值对应。我想在保持各自价值的同时洗牌他们两个。我该怎么做?
由于两个数组的大小相同,您可以使用 Numpy Array Indexing.
def unison_shuffled_copies(a, b):
assert len(a) == len(b) # don't need if we know array a and b is same length
p = numpy.random.permutation(len(a)) # generate the shuffled indices
return a[p], b[p] # make the shuffled copies using same arrangement according to p
这是参考 this answer,有一些变化。
您可以通过 get_state() and reset it between shuffles with set_state() 跟踪 numpy.random.state
。这将使洗牌在两个数组上的行为相同。
import numpy as np
arr1 = np.arange(9).reshape((3, 3))
arr2 = np.arange(10,19).reshape((3, 3))
arr1, arr2
# array([[0, 1, 2],
# [3, 4, 5],
# [6, 7, 8]]),
# array([[10, 11, 12],
# [13, 14, 15],
# [16, 17, 18]])
# get state
state = np.random.get_state()
np.random.shuffle(arr1)
arr1
# array([[6, 7, 8],
# [3, 4, 5],
# [0, 1, 2]])
# reset state and shuffle other array
np.random.set_state(state)
np.random.shuffle(arr2)
arr2
#array([[16, 17, 18],
# [13, 14, 15],
# [10, 11, 12]])