pandas Series/DataFrame获取n个最大值(largest values)和n个最小值((smallest values))

使用pandas时,想要获取一个序列中最大的N个值,和最小N个数值

经过查阅,pandas自带两个方法可以直接获取最大:nlargest和最小:nsmallest。

nlargest

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.nlargest.html#pandas.Series.nlargest

nsmallest

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.nsmallest.html#pandas.Series.nsmallest

使用样例:

data = [
    {"content": "1", "title": "刘德华", "info": "", "time": 1578877014},
    {"content": "2", "title": "刘德华", "info": "", "time": 1579877014},
    {"content": "3", "title": "刘德华", "info": "", "time": 1582877014},
    {"content": "12", "title": "苹果", "info": "", "time": 1582876014},
    {"content": "33", "title": "apple", "info": "", "time": 1581877014},
    {"content": "16", "title": "banana", "info": "", "time": 1561877014},
]

import pandas as pd

s = pd.Series(data)

# 最大3个值
print(pd.to_numeric(s.str.get('content'),errors='coerce').nlargest(3,keep='all'))
>>> 33,16,12

# 最小3个值
print(pd.to_numeric(s.str.get('content'),errors='coerce').nsmallest(3,keep='all'))
>>> 1,2,3

原文网址:

pandas Series/DataFrame获取n个最大值(largest values)和n个最小值((smallest values))

 

  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值