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

如何将Pandas DataFrame转换为每行对应{x:索引,y:值列表}的字典列表?

将Pandas DataFrame转换为每行对应字典的列表的方法

构造示例DataFrame

先还原你提供的DataFrame:

import pandas as pd

data = {
    'Open': [1.9000, 1.8881, 1.9350],
    'High': [1.91, 1.95, 1.95],
    'Low': [1.86, 1.88, 1.86],
    'Close': [1.8850, 1.9400, 1.8956]
}
index = pd.to_datetime(['2021-12-15 12:30:00', '2021-12-15 13:30:00', '2021-12-15 14:30:00'])
df = pd.DataFrame(data, index=index)

方法1:使用iterrows()遍历(直观易理解)

通过逐行遍历提取索引和行值,构造目标字典:

result = []
for idx, row in df.iterrows():
    # 将datetime索引转为字符串格式(若需保留Timestamp对象可去掉strftime)
    result.append({
        'x': idx.strftime('%Y-%m-%d %H:%M:%S'),
        'y': row.tolist()
    })

方法2:使用apply()+lambda(简洁写法)

一行代码完成转换,效率优于普通循环:

result = df.apply(
    lambda row: {
        'x': row.name.strftime('%Y-%m-%d %H:%M:%S'),
        'y': row.tolist()
    },
    axis=1
).tolist()

输出结果

打印result会得到你期望的格式:

[
    {'x': '2021-12-15 12:30:00', 'y': [1.9, 1.91, 1.86, 1.885]},
    {'x': '2021-12-15 13:30:00', 'y': [1.8881, 1.95, 1.88, 1.94]},
    {'x': '2021-12-15 14:30:00', 'y': [1.935, 1.95, 1.86, 1.8956]}
]

注意:如果不需要将datetime索引转为字符串,直接保留原始Timestamp对象,删除.strftime('%Y-%m-%d %H:%M:%S')即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 06:45:36