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

如何在pandas DataFrame中提取单列值最高前三行并格式化输出

pandas按准确率排序取前三输出指定格式文本

问题场景

现有如下结构的pandas DataFrame,其中列0存储特征数量,列1存储对应模型准确率:

0   1
0   10  0.9679487179487178
1   38  0.9692307692307693
2   24  0.9833333333333332
3   62  0.9525641025641025
4   17  0.9679487179487178
5   23  0.9679487179487178
6   72  0.9679487179487178
7   22  0.9538461538461538
8   90  0.9525641025641025
9   32  0.9666666666666668

需要实现:按准确率列做降序排列,取排名前三的记录,按指定格式依次输出最高、第二高、第三高的准确率数值以及对应使用的特征数量,目标输出格式如下:

Highest accuracy was 0.9833333333333332 using 24 features, second highest accuracy was 0.9692307692307693 with 38 features, third highest accuracy was at 0.9679487179487178 with 10 features

实现代码

import pandas as pd

# --- 以下为示例数据构造,已有现成DataFrame可直接跳过 ---
df = pd.DataFrame({
    0: [10, 38, 24, 62, 17, 23, 72, 22, 90, 32],
    1: [
        0.9679487179487178, 0.9692307692307693, 0.9833333333333332,
        0.9525641025641025, 0.9679487179487178, 0.9679487179487178,
        0.9679487179487178, 0.9538461538461538, 0.9525641025641025,
        0.9666666666666668
    ]
})
# --- 示例数据构造结束 ---

# 按准确率列(列索引1)降序排序,取前3条记录
top3_records = df.sort_values(by=1, ascending=False).head(3).reset_index(drop=True)

# 按指定格式拼接输出字符串
result = (
    f"Highest accuracy was {top3_records.loc[0, 1]} using {top3_records.loc[0, 0]} features, "
    f"second highest accuracy was {top3_records.loc[1, 1]} with {top3_records.loc[1, 0]} features, "
    f"third highest accuracy was at {top3_records.loc[2, 1]} with {top3_records.loc[2, 0]} features"
)

# 打印结果
print(result)

实现说明

  • 核心排序逻辑通过pandas的sort_values方法实现,指定ascending=False完成降序排列
  • 取排序后结果的前3行,通过索引依次提取对应位置的准确率、特征数填入字符串模板即可
  • 运行代码后输出内容和目标要求完全匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 15:33:13