python - Filtering dataframe rows based on count
问题描述
I have a table like
Fruit Month
----------------
A Jan
A Feb
A Mar
B Sep
I want to filter the table in such a way that I get only top n rows say two for each fruit Example
Fruit Month
----------------
A Jan
A Feb
B Sep
解决方案
You can just use groupby()
and head()
:
df.groupby('Fruit').head(2)
Outputs:
Fruit Month
0 A Jan
1 A Feb
3 B Sep
推荐阅读
- javascript - 如何在axios中得到正确的答案形式
- reflection - 如何使用 callBy() 调用 Kotlin 配套工厂方法?
- javascript - 在 2 个表单之间动态传递输入数据
- nginx - nginx 返回部分响应
- apache-flink - Flink Kinesis Consumer 未存储最后成功处理的序列号
- pdf - PDFplumber 密码和 check_extractable
- python - django urls.py 更改未反映
- mysql - 如何修复 Visual Studio 中任何可用插件都不支持的身份验证方法caching_sha2_password
- python - 使用 lambda 函数创建 aws sagemker 端点
- apache-spark - Hive 中的 import table 命令如何获取架构?