我想获得列表中最低的 10% 数字。
List = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
Run Code Online (Sandbox Code Playgroud)
从上面的列表中,我期望得到结果。结果 = [1,2],这是列表中最低的 10%。
如果每个元素都是唯一的,您可以简单地对数据进行排序和切片
l = list(range(1, 21))
number_value_to_get = len(l)//10
print(sorted(l)[:number_value_to_get]
Run Code Online (Sandbox Code Playgroud)
但是,大多数情况下,这是错误的,您可以使用 numpy 版本
import numpy as np
l = np.array(range(1, 21))
threshold = np.percentile(l, 10) # calculate the 10th percentile
print(l[l < threshold]) # Filter the list.
Run Code Online (Sandbox Code Playgroud)
请注意需要定义是否包含 10%
import numpy as np
l = np.array([1]*20)
threshold = np.percentile(l, 10)
print(l[l < np.percentile(l, 10)]) # Gives you empty list
print(l[l <= np.percentile(l, 10)]) # Gives you full list
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1725 次 |
| 最近记录: |