NumPy 中的 numpy.random.permutation() 函数
本教程将介绍在 Python 中升级 NumPy 包的方法。
NumPy 随机排列与 Python 中的 numpy.random.permutation() 函数
numpy.random.permutation() 函数主要用于两个目的:获取序列的随机排列副本和在 Python 中获取随机排列的范围。permutation() 和 shuffle() 函数之间的主要区别在于,如果传递一个数组,permutation() 函数返回原始数组的无序副本。相比之下,shuffle() 函数会打乱原始数组。而且,如果我们传递一个整数,permutation() 函数会为我们提供具有给定长度的随机排列的数字序列,而要执行相同的过程,我们需要使用 numpy.arange() 函数和 shuffle() 函数。以下代码示例演示了 Python 中 permutation() 函数和 shuffle() 函数之间的区别。
示例#1:
import numpy as np
array = np.array([0,1,0,0,4])
shuffled = np.random.permutation(array)
np.random.shuffle(array)
print(shuffled)
print(array)
输出:
[0 0 4 1 0]
[0 4 0 1 0]
示例#2:
permuted = np.random.permutation(5)
print(permuted)
sequence = np.arange(5)
np.random.shuffle(sequence)
print(sequence)
输出:
[3 1 4 0 2]
[4 3 0 1 2]
在第一个示例中,我们演示了将数组传递给两个函数时 permutation() 函数和 shuffle() 函数之间的区别。permutation() 函数返回 array 的混洗副本,而 shuffle() 函数则对原始 array 进行混洗。
在第二个示例中,我们演示了传递整数时 permutation() 函数和 shuffle() 函数之间的区别。permutation(n) 函数返回一个带有 n 个整数元素序列的混洗数组,而要使用 shuffle() 函数模仿这种行为,我们必须首先创建一个 n 个整数序列,其中 np.arange() 函数。shuffle() 函数然后对这个新创建的整数元素序列进行打乱。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn