NumPy 随机模块

NumPy random.permutation() 函数随机排列序列或数组,然后返回它。如果x是多维数组,则仅沿其第一个轴进行打乱。

语法

numpy.random.permutation(x) 

参数

x必填。 指定要排列的数组或列表。如果x是整数,则随机排列np.arange(x)。

返回值

返回排列后的序列或数组范围。

示例:

在下面的示例中,random.permutation() 函数用于排列给定的内容

import numpy as np

x = np.arange(0, 10)
y = np.random.permutation(x)

#显示x和y的内容
print("x contains:", x)
print("y contains:", y) 

上述代码的输出将是:

x contains: [0 1 2 3 4 5 6 7 8 9]
y contains: [8 5 0 1 4 6 2 9 7 3] 

示例:

当函数与多维一起使用时数组,它仅沿第一个轴排列内容。

import numpy as np

x = np.arange(1, 10).reshape(3,3)
y = np.random.permutation(x)

#显示x的内容
print("x contains:")
print(x)

#显示y的内容
print("\ny contains:")
print(y) 

上述代码的输出将是:

x contains:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

y contains:
[[4 5 6]
 [7 8 9]
 [1 2 3]] 

示例:

当该函数使用整数,它随机排列np.arange(x),如下例所示。

import numpy as np

x = np.random.permutation(7)

#显示x的内容
print("x contains:", x) 

上述代码的输出将是:

x contains: [2 6 5 3 1 4 0]