开发者社区> 问答> 正文

dataframe中如何得到按列分组后另一列的第n大的值?

dataframe中如何得到按列分组后另一列的第n大的值?

展开
收起
游客y244y7ln2rlpa 2021-12-05 20:38:10 333 0
1 条回答
写回答
取消 提交回答
  • df = pd.DataFrame({'fruit': ['apple', 'banana', 'orange'] * 2,
                       'taste': np.random.rand(6),
                       'price': np.random.randint(0, 15, 6)})
    
    print(df)
    
    # teste列按fruit分组
    df_grpd = df['taste'].groupby(df.fruit)
    # teste列中banana元素的信息
    x=df_grpd.get_group('banana')
    # 排序并找第2大的值
    s = x.sort_values().iloc[-2]
    print(s)
    
    #>	    fruit     taste  price
    	0   apple  0.521990      7
    	1  banana  0.640444      0
    	2  orange  0.460509      9
    	3   apple  0.818963      4
    	4  banana  0.646138      7
    	5  orange  0.917056     12
    
    #>	0.6404436436085967
    
    
    2021-12-05 22:22:57
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载