如何将Python字典转换为带独立索引列的Pandas DataFrame
问题:将嵌套字典转为带独立索引列的Pandas DataFrame
我有如下Python字典:
d = {'2022-12-21 20:00:00': {'1. open': '135.5900', '2. high': '135.7300', '3. low': '135.5900', '4. close': '135.6700', '5. volume': '18031'}, '2022-12-21 19:45:00': {'1. open': '135.5700', '2. high': '135.6000', '3. low': '135.5500', '4. close': '135.5700', '5. volume': '4253'}}
想要转换为结构如下的Pandas DataFrame(时间戳为独立列,保留默认整数索引):
|timestamp |open |high |low |close|volume 1 |2022-12-21 20:00:00 | 135 |135 | 135 | 135 |18031 2 |2022-12-21 19:45:00 | 134 | 112 | 123 | 231 |24124
我尝试用df = pd.DataFrame.from_dict(d, orient='index')实现,但转换后时间戳成了索引列,请问该如何解决?
解决方案
方法1:利用reset_index()转换索引为列
先按你的方法创建DataFrame,再通过reset_index()把原索引(时间戳)转为普通列,同时重命名列名、清理原始列的名称:
import pandas as pd d = {'2022-12-21 20:00:00': {'1. open': '135.5900', '2. high': '135.7300', '3. low': '135.5900', '4. close': '135.6700', '5. volume': '18031'}, '2022-12-21 19:45:00': {'1. open': '135.5700', '2. high': '135.6000', '3. low': '135.5500', '4. close': '135.5700', '5. volume': '4253'}} # 初始转换 df = pd.DataFrame.from_dict(d, orient='index') # 将索引转为列,并重命名为timestamp df = df.reset_index().rename(columns={'index': 'timestamp'}) # 清理列名:去掉数字和点号 df.columns = [col.split('. ')[-1] if '. ' in col else col for col in df.columns] # 转换数值列类型(原始值是字符串) numeric_cols = ['open', 'high', 'low', 'close', 'volume'] df[numeric_cols] = df[numeric_cols].apply(pd.to_numeric) # 默认已保留整数索引,无需额外处理 print(df)
执行后输出的DataFrame符合需求:
timestamp open high low close volume 0 2022-12-21 20:00:00 135.59 135.73 135.59 135.67 18031 1 2022-12-21 19:45:00 135.57 135.60 135.55 135.57 4253
方法2:提前整理数据结构再创建DataFrame
直接把字典转换成列表形式的记录,再传入pd.DataFrame(),这种方式更直接:
import pandas as pd d = {'2022-12-21 20:00:00': {'1. open': '135.5900', '2. high': '135.7300', '3. low': '135.5900', '4. close': '135.6700', '5. volume': '18031'}, '2022-12-21 19:45:00': {'1. open': '135.5700', '2. high': '135.6000', '3. low': '135.5500', '4. close': '135.5700', '5. volume': '4253'}} # 整理成列表记录 records = [] for timestamp, data in d.items(): record = {'timestamp': timestamp} # 遍历子字典,清理键名 for key, value in data.items(): clean_key = key.split('. ')[-1] record[clean_key] = value records.append(record) # 创建DataFrame并转换数值类型 df = pd.DataFrame(records) numeric_cols = ['open', 'high', 'low', 'close', 'volume'] df[numeric_cols] = df[numeric_cols].apply(pd.to_numeric) print(df)
这个方法得到的结果和方法1一致,且不需要处理索引转换的步骤。
内容的提问来源于stack exchange,提问作者Spartex
相关产品推荐
相关产品推荐

