python pandas 3 smallest & 3 largest values

前端 未结 5 1007
误落风尘
误落风尘 2021-01-20 03:03

How can I find the index of the 3 smallest and 3 largest values in a column in my pandas dataframe? I saw ways to find max and min, but none to get the 3.

5条回答
  •  深忆病人
    2021-01-20 03:28

    In [55]: import numpy as np               
    
    In [56]: import pandas as pd              
    
    In [57]: s = pd.Series(np.random.randn(5))
    
    In [58]: s
    Out[58]: 
    0    0.152037
    1    0.194204
    2    0.296090
    3    1.071013
    4   -0.324589
    dtype: float64
    
    In [59]: s.nsmallest(3) ## s.drop_duplicates().nsmallest(3); if duplicates exists               
    Out[59]: 
    4   -0.324589
    0    0.152037
    1    0.194204
    dtype: float64
    
    In [60]: s.nlargest(3) ## s.drop_duplicates().nlargest(3); if duplicates exists             
    Out[60]: 
    3    1.071013
    2    0.296090
    1    0.194204
    dtype: float64
    

提交回复
热议问题