如何将Pandas列中存储的嵌套买卖盘深度JSON展开为扁平化字段列
嵌套JSON深度列扁平化解决方案
实现代码
首先导入依赖包,构建演示用DataFrame:
import pandas as pd import json # 演示用DataFrame构造 a = {'buy': [{'quantity': 51, 'price': 2275.85, 'orders': 2}, {'quantity': 38, 'price': 2275.8, 'orders': 2}, {'quantity': 108, 'price': 2275.75, 'orders': 3}, {'quantity': 120, 'price': 2275.7, 'orders': 2}, {'quantity': 6, 'price': 2275.6, 'orders': 1}], 'sell': [{'quantity': 353, 'price': 2276.95, 'orders': 1}, {'quantity': 29, 'price': 2277.0, 'orders': 2}, {'quantity': 54, 'price': 2277.1, 'orders': 2}, {'quantity': 200, 'price': 2277.2, 'orders': 1}, {'quantity': 4, 'price': 2277.25, 'orders': 1}]} c = {'depth': a} df = pd.DataFrame([c,c])
如果depth列为JSON字符串格式,先转换为Python字典:
df['depth'] = df['depth'].apply(json.loads)
核心扁平化处理逻辑:
def flatten_depth(depth_dict): flat_res = {} # 处理5档买盘数据 for idx, buy_item in enumerate(depth_dict['buy'], start=1): for k, v in buy_item.items(): flat_res[f'depth.buy.{k}{idx}'] = v # 处理5档卖盘数据 for idx, sell_item in enumerate(depth_dict['sell'], start=1): for k, v in sell_item.items(): flat_res[f'depth.sell.{k}{idx}'] = v return flat_res # 生成扁平化后的深度数据DataFrame flat_depth_df = pd.DataFrame(df['depth'].apply(flatten_depth).tolist()) # 若需保留原表其他列,执行合并操作 final_df = pd.concat([df.drop('depth', axis=1), flat_depth_df], axis=1)
输出说明
运行后final_df的列格式与需求完全匹配,示例列包括:
depth.buy.quantity1、depth.buy.price1、depth.buy.orders1depth.sell.quantity1、depth.sell.price1、depth.sell.orders1
依次类推到第5档的所有字段。
内容的提问来源于stack exchange,提问作者Suraj Shejal
相关产品推荐
相关产品推荐

