Python中的Numpy percentile()方法示例
Numpy percentile()方法用于计算沿指定轴使用数组提供的输入数据的第i个百分点。但是百分位数是什么意思?百分位是统计中通常使用的数学术语。一组数据的第i个百分位数是i%的数据低于该百分数的值。使用np percentile()方法,可以在Python中计算百分比。
为了更好地理解,我们可以考虑某个学生在100分中获得90个百分点,那么这意味着在100名学生中,该特定学生的人数超过90名,并且低于他。
句法
numpy.percentile (arr, i, axis=None, out=None)
参量
percentile()函数最多包含四个参数:
arr:类似于array_,输入数组或可以转换为类似于列表的数组的对象。
i:百分位值,必须在0-100的范围内(0和100为包含值)。
轴:这是一个可选参数。它代表我们要计算百分比的轴。如果未给出轴值,则默认情况下,应该将输入数组展平,然后计算百分位值(整个轴)。如果设置axis = 0,则沿列计算百分比,如果axis = 1,则沿行计算百分比。
out:ndarray,它也是一个可选参数。它代表一个可选的结果数组,我们要在其中获得输出。要注意的是,该阵列的形状应与期望的输出匹配。
返回值
它返回标量或ndarray。该方法返回第i个百分位值。当轴值设置为“无”时,将返回标量值。否则,当指定轴时,将返回n维数组,其沿指定轴的百分比值为百分数。
编程范例
该程序显示一维数组/矢量情况下numpy.percentile()方法的工作。
# importing the numpy module import numpy as np # Making a list lst = [16, 18, 22, 14, 22, 23, 28, 17, 19, 15, 16, 22, 14, 16, 18] print("Given list is:n", lst) # Calculating percentile value in the list res = np.percentile(lst, 35) print("35th percentile of given list is: ", res) # Creating an array arr = np.array([100, 200, 150, 125, 175, 150]) print("nArray elements are:n", arr) # Calculating percentile value in the list output = np.percentile(arr, 75) print("75th percentile of given array is: ", output)
输出量
Given list is: [16, 18, 22, 14, 22, 23, 28, 17, 19, 15, 16, 22, 14, 16, 18] 35th percentile of given list is: 16.0 Array elements are: [100 200 150 125 175 150] 75th percentile of given array is: 168.75
说明
在上面的程序中,我们获取了一个名为lst的列表,该列表由一些随机整数组成,然后我们计算了列表中的第35个百分位数。同样,使用另一个名为arr的数组,然后我们在数组中显示了第75个百分位值。
程序以显示numpy.percentile()方法在多维数组的情况下的工作:
请参阅以下代码。
# importing the numpy module import numpy as np # Making a 2D array arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) print("Elements in the 2D array are:n", arr) out = np.percentile(arr, 50) print("Calculating 50th percentile without specifying axis: ", out) out0 = np.percentile(arr, 50, axis=0) print("Calculating 50th percentile along axis 0: ", out0) out1 = np.percentile(arr, 50, axis=1) print("Calculating 50th percentile along axis 1: ", out1)
输出量
Elements in the 2D array are: [[10 20 30] [40 50 60] [70 80 90]] Calculating 50th percentile without specifying axis: 50.0 Calculating 50th percentile along axis 0: [40. 50. 60.] Calculating 50th percentile along axis 1: [20. 50. 80.]
说明
在程序中,我们采用了一个名为arr的二维数组,然后将其内容显示在该数组中。
以三种模式计算给定数组的第50个百分点值:
首先,当我们未指定任何轴时,结果将成为标量值,因为默认情况下,应该将输入数组展平。
其次,当我们计算沿轴0的百分位值时,则随列一起计算百分位值。其结果使用out0显示。
最后,当我们沿轴1计算百分值时,则沿行计算百分值。使用out1显示其结果。
因此,这就是在Python中计算百分位数的方式。
最后,Numpy percentile()方法示例结束。
也可以看看
numpy matmul()
numpy convolve()
numpy related()
numpy polyfit()
numpy内部()