Numpy 将相同的随机排列应用于具有相同形状的两个不同的 ndarray
Numpy apply the same random permutation to two different ndarray with the same shape
假设我有两个 NumPy 数组,比如说,每个数组的形状都是 (N,1)。第一个数组是一个名为 Age 的数组,第二个数组称为 income。假设这些属性是不同人的样本,那么 ith
索引指的是样本中的 ith
人,通过知道 i
我可以检索他的年龄和收入。
现在假设我想随机(或确定性地)排列两个数组,以便两者都进行相同的排列?我的意思是,排列后,两个数组的索引j
指的是同一个人的属性?
我知道这样做的一种方法是定义具有两个属性的人的对象:age
和 income
,但我想要这样做的 Numpy 方式。
谢谢。
您可以先创建一个索引排列,然后使用相同的索引排列访问两个数组。例如,这可以使用 numpy.random.permutation
来完成。
示例:
>>> age = np.random.randint(0,100,10)
>>> income = np.random.randint(0,10000,10)
>>> age
array([38, 4, 70, 16, 8, 29, 1, 41, 54, 60])
>>> income
array([4797, 5884, 8005, 5696, 7577, 6386, 3314, 3574, 5422, 409])
>>> permutation_indices = np.random.permutation(10)
>>> permutation_indices
array([9, 1, 8, 0, 7, 3, 2, 6, 5, 4])
>>> age[permutation_indices]
array([60, 4, 54, 38, 41, 16, 70, 1, 29, 8])
>>> income[permutation_indices]
array([ 409, 5884, 5422, 4797, 3574, 5696, 8005, 3314, 6386, 7577])
假设我有两个 NumPy 数组,比如说,每个数组的形状都是 (N,1)。第一个数组是一个名为 Age 的数组,第二个数组称为 income。假设这些属性是不同人的样本,那么 ith
索引指的是样本中的 ith
人,通过知道 i
我可以检索他的年龄和收入。
现在假设我想随机(或确定性地)排列两个数组,以便两者都进行相同的排列?我的意思是,排列后,两个数组的索引j
指的是同一个人的属性?
我知道这样做的一种方法是定义具有两个属性的人的对象:age
和 income
,但我想要这样做的 Numpy 方式。
谢谢。
您可以先创建一个索引排列,然后使用相同的索引排列访问两个数组。例如,这可以使用 numpy.random.permutation
来完成。
示例:
>>> age = np.random.randint(0,100,10)
>>> income = np.random.randint(0,10000,10)
>>> age
array([38, 4, 70, 16, 8, 29, 1, 41, 54, 60])
>>> income
array([4797, 5884, 8005, 5696, 7577, 6386, 3314, 3574, 5422, 409])
>>> permutation_indices = np.random.permutation(10)
>>> permutation_indices
array([9, 1, 8, 0, 7, 3, 2, 6, 5, 4])
>>> age[permutation_indices]
array([60, 4, 54, 38, 41, 16, 70, 1, 29, 8])
>>> income[permutation_indices]
array([ 409, 5884, 5422, 4797, 3574, 5696, 8005, 3314, 6386, 7577])