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

如何将defaultdict转换为含close与vol双列的Pandas DataFrame

解决defaultdict转DataFrame时保留键和值的问题

嘿,我来帮你搞定这个问题!你之前的方法出错是因为直接遍历字典时默认只会拿到键,所以转字符串再分割的操作自然就丢了值。其实Pandas有非常直接的方法把字典(包括defaultdict)转换成带两列的DataFrame,不用绕弯子转字符串。

方法1:直接用字典的items()构造DataFrame

字典的items()方法会返回所有(键, 值)对的列表,刚好可以直接传给pd.DataFrame,再指定列名就行:

import pandas as pd
from collections import defaultdict

# 你的sum_vol数据
sum_vol = defaultdict(int, {2930.0: 2838, 2930.25: 677, 2930.5: 2780, 2931.0: 2005, 2931.75: 1402, 2932.0: 711, 2932.5: 2982, 2931.5: 1500, 2932.75: 7973, 2933.0: 12170, 2933.75: 10009, 2934.5: 49867, 2932.25: 1758})

# 转换为DataFrame
df = pd.DataFrame(sum_vol.items(), columns=['close', 'vol'])

运行后你就能得到想要的结果:

closevol
029302838
12930.25677
22930.52780
329312005
.........

方法2:用from_dict方法(适合更灵活的场景)

如果你想先把键作为索引,再转成列,可以用from_dict指定orient='index',之后重置索引并重命名列:

df = pd.DataFrame.from_dict(sum_vol, orient='index', columns=['vol']).reset_index().rename(columns={'index': 'close'})

这个方法和方法1的结果完全一致,只是操作路径不同。

为什么你的原方法会失败?

你之前的代码里,str(x) for x in sum_vol其实是在遍历字典的键(Python中遍历字典默认只取键),所以拼接后的字符串只有键的内容,分割后自然只能得到close列,完全丢失了值。这种转字符串再分割的方式既麻烦又容易出错,直接用Pandas提供的字典转DataFrame方法才是最优解。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 13:12:37