numpy.ptp()
方法沿指定的轴计算数组中值的范围(最大值 - 最小值)。此处,**ptp** 代表 **peak to peak**(峰峰值)。
示例
import numpy as np
# create an array
array1 = np.array([1, 2, 3, 4, 5, 6, 7])
# calculate the range of the array
range = np.ptp(array1)
print(range)
# Output: 6
ptp() 语法
numpy.ptp()
方法的语法如下:
numpy.ptp(array, axis = None, out = None, keepdims = <no value>)
ptp() 参数
numpy.ptp()
方法接受以下参数:
array
- 包含所需范围的数字的数组(可以是array_like
)axis
(可选) - 计算范围的轴(int
或tuple of int
)out
(可选) - 用于放置结果的输出数组(ndarray
)keepdims
(可选) - 指定是否保留原始数组的维度(bool
)
注意: ptp()
参数的默认值有以下含义:
axis = None
,即计算整个数组的范围。- 默认情况下,不传递
keepdims
。
ptp() 返回值
numpy.ptp()
方法沿指定的轴返回数组中值的范围(最大值 - 最小值)。
注意:如果给定轴中的某个元素是 NaN
,numpy.ptp()
也会返回 NaN
。
示例 1:查找 ndArray 的范围
import numpy as np
# create an array
array1 = np.array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
# find the range of entire array
range1 = np.ptp(array1)
# find the range across axis 0
range2 = np.ptp(array1, 0)
# find the range across axis 0 and 1
range3 = np.ptp(array1, (0, 1))
print('\nRange of the entire array:', range1)
print('\nRange across axis 0:\n', range2)
print('\nRange across axis 0 and 1', range3)
输出
Range of the entire array: 7 Range across axis 0: [[4 4] [4 4]] Range across axis 0 and 1 [6 6]
示例 2:使用可选的 keepdims 参数
如果将 keepdims
设置为 True
,则结果范围数组与原始数组具有相同的维度数。
import numpy as np
array1 = np.array([[1, 2, 3],
[4, 5, 6]])
# keepdims defaults to False
result1 = np.ptp(array1, axis = 0)
# pass keepdims as True
result2 = np.ptp(array1, axis = 0, keepdims = True)
print('Dimensions in original array:', array1.ndim)
print('Without keepdims:', result1, 'with dimensions', result1.ndim)
print('With keepdims:', result2, 'with dimensions', result2.ndim)
输出
Dimensions in original array: 2 Without keepdims: [3 3 3] with dimensions 1 With keepdims: [[3 3 3]] with dimensions 2
示例 3:使用可选的 out 参数
out
参数允许我们指定一个输出数组来存储结果。
import numpy as np
array1 = np.array([[12, 21, 13],
[41, 15, 6]])
# create an output array
output = np.zeros(3)
# compute range and store the result in the output array
np.ptp(array1, out = output, axis = 0)
print('Range:', output)
输出
Range: [29. 6. 7.]
示例 4:ptp() 的数据类型
numpy.ptp()
方法没有参数可以指定结果将存储的输出数组的数据类型。这是因为它将使用与原始数组元素相同的数据类型。
import numpy as np
array1 = np.array([[127, 127, 127],
[1, 0, -1]], dtype = np.int8)
# compute range and store the result in the output array
output = np.ptp(array1, axis = 0)
# print the range of the array
print('Range:', output)
# print the data type of the output array
print('Data Type of output array:', output.dtype)
输出
Range: [ 126 127 -128] Data Type of output array: int8
在此示例中,给定的数据类型是 np.int8
,范围从 **-128** 到 **127**。
对于第三列,峰峰值为 127 - (-1) = 128
,超出了 np.int8
的范围,因此结果为 **-128**。
注意:当输入是符号整数数组时,可能会返回负值。