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

如何从嵌套字典提取指定价格值并插入Pandas新列(无循环)

可行方案:提取嵌套字典中目标值并生成Pandas新列

无需显式循环即可实现需求,具体步骤如下:

  1. 将原始嵌套字典转换为Pandas DataFrame,以合约代码作为索引
  2. 使用apply结合lambda表达式,提取每个条目下depth->buy列表第一个元素的price值,生成新列

完整代码示例

import pandas as pd

# 原始嵌套字典
data = {
    'NSE_FO:NIFTY28DEC21000CE': {'ohlc': None,
  'depth': {'buy': [{'quantity': 0, 'price': 0.0, 'orders': 0},
    {'quantity': 1, 'price': 3.0, 'orders': 1},
    {'quantity': 1, 'price': 3.0, 'orders': 1}],
   'sell': [{'quantity': 0, 'price': 0.0, 'orders': 0},
    {'quantity': 1, 'price': 3.0, 'orders': 1},
    {'quantity': 1, 'price': 3.0, 'orders': 1}]},
  },
 'NSE_FO:NIFTY28DEC24000CE': {'ohlc': None,
  'depth': {'buy': [{'quantity': 1, 'price': 3.0, 'orders': 0},
    {'quantity': 1, 'price': 1.0, 'orders': 1},
    {'quantity': 2, 'price': 2.0, 'orders': 1}],
   'sell': [{'quantity': 0, 'price': 0.0, 'orders': 0},
    {'quantity': 3, 'price': 3.0, 'orders': 1},
    {'quantity': 4, 'price': 4.0, 'orders': 1}]},
  },
 'NSE_FO:NIFTY28DEC28000PE': {'ohlc': {'open': 0.0,
   'high': 0.0,
   'low': 0.0,
   'close': 0.0},
  'depth': {'buy': [{'quantity': 250, 'price': 1040.05, 'orders': 1},
    {'quantity': 4, 'price': 1.0, 'orders': 1},
    {'quantity': 2, 'price': 3.0, 'orders': 1}],
   'sell': [{'quantity': 0, 'price': 0.0, 'orders': 1},
    {'quantity': 3, 'price': 3.0, 'orders': 1},
    {'quantity': 4, 'price': 4.0, 'orders': 1}]},
  }
}

# 转换为DataFrame
df = pd.DataFrame.from_dict(data, orient='index')

# 提取目标值生成新列
df['first_buy_price'] = df['depth'].apply(lambda x: x['buy'][0]['price'])

# 输出新列结果
print(df['first_buy_price'])

输出结果

NSE_FO:NIFTY28DEC21000CE       0.00
NSE_FO:NIFTY28DEC24000CE       3.00
NSE_FO:NIFTY28DEC28000PE    1040.05
Name: first_buy_price, dtype: float64

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 00:31:12