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

技术问询:提取每行/按ID的前两大值列名并生成新列

嘿,这两个数据表处理需求我熟得很,用Python的pandas就能轻松搞定,下面分情况给你详细的代码和说明:

需求1:提取每行最高值与第二高值对应的列名,新增至数据表

假设你的数据表是包含数值型列的DataFrame,我们可以对每行的数值排序,提取前两名对应的列名,拼接成新列:

import pandas as pd

# 先整个示例数据方便你测试
sample_data = {
    'Score_Math': [85, 92, 78],
    'Score_English': [90, 88, 82],
    'Score_Science': [88, 95, 80]
}
df = pd.DataFrame(sample_data)

# 定义函数:获取单行前两大值的列名,用逗号分隔
def get_top_two_columns(row):
    # 对当前行按数值降序排序,取前两个索引(也就是列名)
    top_two = row.sort_values(ascending=False).index[:2]
    return ', '.join(top_two)

# 新增列存储结果
df['Top_Two_Subjects'] = df.apply(get_top_two_columns, axis=1)

如果你的数据表混有非数值列,记得先筛选出数值型列来处理,比如用df_numeric = df.select_dtypes(include=['int64', 'float64']),处理完后再把结果合并回原表就行。

需求2:按ID分组,提取每组失败原因前两大的列名,拼接成新列

这里分两种常见的数据结构场景来处理:

场景1:失败原因是多列数值(比如各原因的发生次数)

比如数据表有ID列,以及多个以失败原因命名的列,值是该原因的计数:

# 示例数据
fail_data = {
    'ID': ['User001', 'User001', 'User002', 'User002'],
    'Fail_Login': [3, 2, 5, 1],
    'Fail_Payment': [1, 4, 2, 6],
    'Fail_Loading': [2, 1, 3, 2]
}
df_fail = pd.DataFrame(fail_data)

# 先按ID分组,对各失败原因列求和(你也可以用count/max,看实际需求)
grouped_fails = df_fail.groupby('ID')[['Fail_Login', 'Fail_Payment', 'Fail_Loading']].sum()

# 提取每组前两大的失败原因列名
def get_top_two_failures(group):
    top_two = group.sort_values(ascending=False).index[:2]
    return ', '.join(top_two)

# 生成每组的结果,再合并回原表
top_fail_results = grouped_fails.apply(get_top_two_failures, axis=1).reset_index(name='Top_Two_Failures')
df_fail = df_fail.merge(top_fail_results, on='ID')

场景2:失败原因是单列字符串(每行是一条失败记录)

如果数据表是每行对应一次失败,失败原因存在单独的字符串列里,我们需要先统计每个ID下各原因的出现次数,再取前二:

# 示例数据
fail_record_data = {
    'ID': ['User001', 'User001', 'User001', 'User002', 'User002'],
    'Failure_Reason': ['Fail_Login', 'Fail_Payment', 'Fail_Login', 'Fail_Payment', 'Fail_Loading']
}
df_fail_records = pd.DataFrame(fail_record_data)

# 统计每个ID各失败原因的出现次数
reason_count = df_fail_records.groupby('ID')['Failure_Reason'].value_counts().unstack(fill_value=0)

# 获取每组前两大的失败原因
top_reason_results = reason_count.apply(
    lambda x: ', '.join(x.sort_values(ascending=False).index[:2]), 
    axis=1
).reset_index(name='Top_Two_Failures')

# 合并回原表
df_fail_records = df_fail_records.merge(top_reason_results, on='ID')

以上代码都可以直接运行测试,你可以根据自己的实际数据表结构调整列名和聚合方式~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:45:41