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

如何对pandas DataFrame列表列的每个元素累加对应整数列的数值

解决方法

方法1:pandas原生实现(性能最优,推荐)

import pandas as pd

# 示例DataFrame(补充元素为字符串避免变量未定义报错)
df = pd.DataFrame({
    "list": [["a", "b", "c"], ["a", "c", "d"], ["c"]],
    "count": [3, 5, 1]
})

# 拆分列表列、分组求和、转字典
result = df.explode("list").groupby("list")["count"].sum().to_dict()
print(result)

运行后输出与预期完全一致:{'a': 8, 'b': 3, 'c': 9, 'd': 5}

方法2:遍历累加实现(无pandas高阶API依赖)

from collections import defaultdict

res = defaultdict(int)
for item_list, count_val in zip(df["list"], df["count"]):
    for ele in item_list:
        res[ele] += count_val

result = dict(res)
print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:39:03