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

如何用Python Pandas按ID将DataFrame的Valor列合并为列表?

Pandas按ID合并Valor列为列表的实现方法

首先创建示例DataFrame:

import pandas as pd

df = pd.DataFrame({
    'ID': [1, 1, 1, 2, 3, 3],
    'Valor': [15, 10, 25, 13, 10, 11]
})

核心实现代码

通过groupby分组后,用自定义逻辑处理单值和多值的展示差异:

# 自定义聚合函数:多值转列表,单值保持原始格式
def aggregate_values(x):
    return x.tolist() if len(x) > 1 else x.iloc[0]

# 分组聚合并重置索引,得到目标格式
result_df = df.groupby('ID')['Valor'].agg(aggregate_values).reset_index()

也可以用lambda函数简化成一行代码:

result_df = df.groupby('ID')['Valor'].agg(lambda x: x.tolist() if len(x) > 1 else x.iloc[0]).reset_index()

结果验证

运行后result_df的输出与需求完全匹配:

IDValor
1[15, 10, 25]
213
3[10, 11]

内容的提问来源于stack exchange,提问作者Gabriel Vieira Lima

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 20:35:15