NumPy ptp()
函数
在本教程中,我们将介绍 NumPy 库的numpy.ptp()
功能。
在统计功能numpy.ptp()
中,“ ptp 代表峰到峰。
该功能用于沿轴返回一系列值。
可以使用范围=最大值-最小值来计算范围。
numpy.ptp()
的语法:
使用该函数所需的语法如下:
numpy.ptp(a, axis=None, out=None, keepdims=<no value>)
参数:
下面是这个函数接受的参数的描述:
a 该参数用于指示输入数组。
轴 这个参数用来表示我们想要取范围值的轴。默认情况下,输入数组被展平(即在所有轴上工作)。这里轴= 0 表示沿列的,轴= 1 表示沿行的工作。
out 这是一个可选的参数,用于指示一个备选数组,我们希望在其中存储该函数的结果或输出。阵列必须具有与预期输出相同的尺寸。
返回值:
此函数返回数组的范围(如果轴为无,它将返回标量值)或具有沿指定轴的值范围的数组。
例 1:
在下面给出的代码片段中,我们将 1D 数组的最后一个元素作为 NaN ,并检查结果:
import numpy as np
input_arr = [1, 10, 7, 20, 11, np.nan]
print("The Input array is : ")
print(input_arr)
print("The Range of input array is : ")
print(np.ptp(input_arr))
输入数组为: 【1,10,7,20,11,nan】 输入数组的范围为: nan
注: 若阵中某值为 NaN 则其范围也为 NaN 。
现在,我们将采用一个包含所有数字的 1D 阵列:
import numpy as np
input_arr = [1, 10, 7, 20,11,56,67]
print("The Input array is : ")
print(input_arr)
print("The Range of input array is : ")
print(np.ptp(input_arr))
输入数组为: 【1,10,7,20,11,56,67】 输入数组的范围为: 66
例 2:
现在我们将举另一个例子,我们将使用这个函数的不同参数:
import numpy as np
inp = [[15, 18, 16, 63, 44], [19, 4, 29, 5, 20], [24, 4, 54, 6, 4,]]
print("\nThe Input array is:")
print(inp)
# The Range of the flattened array is calculated as:
print("\nThe Range of the array when the axis = None : ")
print(np.ptp(inp))
# The Range along the first axis where axis=0 means vertical
print("The Range of the array when the axis = 0 : ")
print(np.ptp(inp, axis = 0))
# Range along the second axis where axis=1 means horizontal
print("The Range of the array when the axis = 1: ")
print(np.ptp(inp, axis = 1))
输入数组为: 【【15,18,16,63,44】、【19,4,29,5,20】、【24,4,54,6,4】】
当轴=无时数组的范围: 59 当轴= 0 时数组的范围: 【9 14 38 58 40】 当轴= 1 时数组的范围: 【40】
摘要
在本教程中,我们介绍了 Numpy 库的numpy.ptp()
统计功能及其语法、参数和返回值以及一些代码示例。