You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jupyter中统计公牛在各指标Top3/Bottom3的出现次数问题

公牛Top3/Bottom3出现次数统计解决方案

问题说明

你已通过nsmallest获取了df_bulls数据集中7项指标(如Weaning Weight(kg)、Weight(kg))的Bottom3数据,但现有代码错误返回列名,需要统计每头公牛在所有Top3/Bottom3列表中的出现次数,以及对应的所属类别,最终得到降序排列的结果。

实现步骤与代码

import pandas as pd

# 1. 生成各指标的Top3/Bottom3数据并添加类别标签
# 示例:生成两个指标的Bottom3,其余5个指标按相同逻辑补充
bottom3_weaning = df_bulls.nsmallest(3, 'Weaning Weight(kg)').assign(category='Bottom3 - Weaning Weight(kg)')
bottom3_weight = df_bulls.nsmallest(3, 'Weight(kg)').assign(category='Bottom3 - Weight(kg)')
# 如果需要统计Top3,用nlargest方法:top3_weaning = df_bulls.nlargest(3, 'Weaning Weight(kg)').assign(category='Top3 - Weaning Weight(kg)')

# 2. 合并所有Top3/Bottom3数据集
all_rank_dfs = [bottom3_weaning, bottom3_weight]  # 补充其余5个指标的结果
combined_df = pd.concat(all_rank_dfs, ignore_index=True)

# 3. 分组统计出现次数与对应类别
result = combined_df.groupby('公牛ID')['category'].agg(
    出现次数='size',
    所属类别=lambda x: ', '.join(x.unique())
).reset_index()

# 4. 按出现次数降序排序
result = result.sort_values('出现次数', ascending=False)

# 输出结果
print(result)

关键逻辑解释

  • assign(category=...):给每个指标的排名结果添加明确的类别标签,避免混淆不同指标的Top/Bottom3
  • pd.concat:将分散的各指标排名数据合并为统一数据集,便于后续批量统计
  • groupby+agg:按公牛ID分组,用size统计出现次数,用lambda函数聚合该公牛所属的所有类别
  • sort_values:实现按出现次数从高到低排序,满足结果格式要求

内容的提问来源于stack exchange,提问作者Jess

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 10:45:34