首页 > 解决方案 > 如何在不使用 heapq.nsmallest 的情况下在一列中找到十个最小值

问题描述

datafrme (image)我试图在我的数据框的一列上找到十个最低值,并找到它们的最小值、最大值和标准。当我使用 heapq.nsmallest(10, a).describe 时,我收到一个错误 AttributeError: 'list' object has no attribute。有没有其他方法可以解决我的问题?

#mean, max, min, std, medium of the ten lowest values of latitude values    
  import heapq
  lat = data['latd']
  heapq.nsmallest(10, lat).describe()

AttributeError                            Traceback (most recent call last)
<ipython-input-13-4d7caab1e14f> in <module>()
      2 import heapq
      3 lat = data['latd']
----> 4 heapq.nsmallest(10, lat).describe()

 AttributeError: 'list' object has no attribute 'describe'

标签: pythonpython-3.xpandasnumpy

解决方案


您可以使用内置的 pandas 方法:

df=pd.DataFrame({'a':[70,69,58,47,36,25,14,53,38,58],'b':[13,24,35,46,57,86,79,80,39,17]})

    a   b
0   70  13
1   69  24
2   58  35
3   47  46
4   36  57
5   25  86
6   14  79
7   53  80
8   38  39
9   58  17

df.nsmallest(5,'a')

    a   b
6   14  79
5   25  86
4   36  57
8   38  39
3   47  46

df.nsmallest(5,'a').describe()


a   b
count   5.000000    5.000000
mean    32.000000   61.400000
std 12.747549   20.452384
min 14.000000   39.000000
25% 25.000000   46.000000
50% 36.000000   57.000000
75% 38.000000   79.000000
max 47.000000   86.000000

对于单列,只需传入单列并在结果系列上调用它

df['a'].nsmallest(5).describe()

推荐阅读