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

如何用Pandas提取每行Top10关联值并转为单行DataFrame结构

问题

需要处理一个关联矩阵(实际含数千个Ref列,示例仅展示少量),目前已实现提取每行最大值对应的Ref与Score,现在要提取每行Top10的Ref及对应Score,并整理为每行包含1_Ref、1_Score、2_Ref、2_Score等字段的DataFrame,尝试stack方法未得到预期结果。

关联矩阵示例

Ref_1          Ref_2
Base_1        0.021088       0.022260   
Base_2        0.022539       0.023792   
Base_3        0.026193       0.027648   
Base_4        0.027209       0.028721   
Base_5        0.000000       0.000000   
Base_6        0.000000       0.000000   

当前提取最大值的代码

data = []

for row_index, row in similarity_df.iterrows():
    max_sim = row.max()
    max_sim_col = row.idxmax()
    data.append([row_index, max_sim_col, max_sim])

result_df = pd.DataFrame(data, columns=['Base', 'Ref', 'Score'])

预期输出结构

Base       1_Ref    1_Score     2_Ref    2_Score     3_Ref   3_Score    etc...
Base_1     Ref_2    0.022260    Ref_1    0.021088    ...
Base_2     Ref_2    0.023792    Ref_1    0.022539    ...

解决方案

用pandas内置方法替代循环,高效提取每行Top10数据并转换为目标格式:

import pandas as pd

def get_top_n(row, n=10):
    # 提取每行前n大的元素,自动按值降序排列
    top_n = row.nlargest(n)
    # 构造交替的Ref和Score序列
    values = []
    for col, val in top_n.items():
        values.extend([col, val])
    # 生成对应列名
    cols = [f"{i+1}_{suffix}" for i in range(n) for suffix in ['Ref', 'Score']]
    return pd.Series(values, index=cols)

# 应用函数到矩阵每行
top10_df = similarity_df.apply(get_top_n, axis=1)
# 将原索引转为Base列
top10_df.reset_index(inplace=True)
top10_df.rename(columns={'index': 'Base'}, inplace=True)

关键说明

  • 避免iterrows循环,适配数千列的大矩阵场景,运行效率更高
  • nlargest(n)直接按值降序提取前n个元素,无需手动排序
  • 自动生成1_Ref/1_Score格式的列名,直接输出符合预期的宽格式DataFrame
  • 全0行(如Base_5、Base_6)会自动填充对应的Ref列名与0值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:32:50