python pandas 3 smallest & 3 largest values

前端 未结 5 1039
误落风尘
误落风尘 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:29

    import pandas as pd
    import numpy as np
    np.random.seed(1)
    x=np.random.randint(1,100,10)
    y=np.random.randint(1000,10000,10)
    
    x
    array([38, 13, 73, 10, 76,  6, 80, 65, 17,  2])
    y
    array([8751, 4462, 6396, 6374, 3962, 3516, 9444, 4562, 5764, 9093])
    
    data=pd.DataFrame({"age":x,
                   "salary":y})
    
    
    data.nlargest(5,"age").nsmallest(5,"salary")
    

提交回复
热议问题