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

Python如何从DataFrame字典中迭代输出并命名各独立DataFrame

问题背景
  • 现有一个名为dfs的DataFrame字典,内部共存储5个DataFrame对象。
  • 基于dfs字典执行分类处理逻辑,将分类结果存入新字典out_dfs,对应执行代码与运行结果如下:
out_dfs = {}
for idx, data in enumerate(list(dfs.values())):
    # 原代码clf.后缺分类器调用方法名,按实际使用的方法补全即可
    out_dfs[idx] = clf.predict(data)
out_dfs

# 运行返回结果
{0: array([-0.01126357,  0.01003442, -0.00631642, -0.00631642,  0.01589343,
         0.00999904,  0.05703701,  0.01549907,  0.01364896,  0.04490213]),
 1: array([-0.01126357, -0.00631642,  0.01572133,  0.01465883,  0.05006177,
         0.0127623 ,  0.00754415,  0.05572284,  0.00996258,  0.00618012,]),
 2: array([-0.01126357,  0.0117059 ,  0.00999904,  0.04732937,  0.01211804,
         0.01238714,  0.0132119 ,  0.01366057,  0.0089514 ,  0.0140865]),
 3: array([-0.01126357,  0.05261424,  0.05785207,  0.03360043,  0.05927981,
         0.05927981,  0.033355  ,  0.0578699 ,  0.05570744,  0.04727342]),
 4: array([-0.01126357,  0.01003442, -0.00631642,  0.0151311 ,  0.05006177,
         0.05785207,  0.05261424,  0.05927981,  0.05572284,  0.05927981])}
实现需求
  • 目前已知可以通过GS = pd.DataFrame(out_dfs.values()).T[0]提取第一个结果序列,需要实现迭代输出所有结果、且为每个独立结果自动命名的方案,期望输出格式如下:
0   -0.011264       0   -0.011264
1    0.010034       1   -0.006316
2   -0.006316       2    0.015721
3   -0.006316       3    0.014659
4    0.015893       4    0.050062
5    0.009999       5    0.012762
6    0.057037       6    0.007544
7    0.015499       7    0.055723
8    0.013649       8    0.009963
9    0.044902       9    0.006180
Name: 0, dtype: float64         Name: 1, dtype: float64
解决方案

不需要先构造全量DataFrame再取列(数据量大时会产生冗余内存开销),直接遍历字典键值对,将每个numpy数组转为带对应名称的pandas Series即可,代码如下:

import pandas as pd

# 遍历out_dfs的索引和对应结果数组
for idx, result_arr in out_dfs.items():
    # 转换为Series,将当前字典键设为序列名称
    named_series = pd.Series(result_arr, name=idx)
    # 调整打印排版和示例一致,两个序列并排输出
    print(named_series, end="\t\t")
    if (idx + 1) % 2 == 0:
        print("\n")

如果需要把命名后的结果存下来后续使用,可以直接存入新的字典:

# 存储所有带名称的Series
named_series_dict = {idx: pd.Series(arr, name=idx) for idx, arr in out_dfs.items()}
# 后续按索引直接取即可,比如取第0个
GS = named_series_dict[0]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 14:51:12