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

如何在Pandas中提取嵌套JSON的Quantity字段值并计算总和

提取嵌套JSON中Quantity值的总和问题

问题背景

给定如下嵌套结构的JSON文件:

[
   {
      "IsRecentlyVerified": true,
      "AddressInfo": {
          "Town": "Haarlem"
      },
      "Connections": [
          {
             "PowerKW": 17,
             "Quantity": 2
          }
       ],
       "NumberOfPoints": 1
    },
    {
      "IsRecentlyVerified": true,
      "AddressInfo": {
          "Town": "Haarlem"
      },
      "Connections": [
          {
             "PowerKW": 17,
             "Quantity": 1
          },
          {
             "PowerKW": 17,
             "Quantity": 1
          },
          {
             "PowerKW": 17,
             "Quantity": 1
          }
       ],
       "NumberOfPoints": 1
    }
]

需求是提取所有Quantity字段的值并计算总和(示例中总和为5)。

尝试的代码及问题

尝试用以下代码处理,但未得到预期结果,调用dfConnections.get("Quantity")返回None:

import json
import pandas as pd

df = pd.read_json("chargingStations.json")

dfConnections = df["Connections"]
dfConnections = pd.json_normalize(dfConnections)

print(dfConnections)

解决方案

方法1:使用pandas的explode展开嵌套列表

df["Connections"]是包含列表的Series,直接用pd.json_normalize无法正确展开每个子元素。可以先通过explode把每个Connections列表中的元素拆成单独行,再进行标准化:

import pandas as pd

# 读取JSON数据
df = pd.read_json("chargingStations.json")

# 展开Connections列中的嵌套列表,每行对应一个子字典
exploded_df = df.explode("Connections", ignore_index=True)

# 标准化展开后的Connections列,提取Quantity字段
connections_normalized = pd.json_normalize(exploded_df["Connections"])

# 计算总和
total_quantity = connections_normalized["Quantity"].sum()
print(total_quantity)  # 输出:5

方法2:纯Python遍历(无需pandas)

如果不需要使用pandas,直接用Python原生的JSON处理更简单:

import json

# 读取JSON文件
with open("chargingStations.json", "r") as f:
    data = json.load(f)

total = 0
# 遍历每个充电站
for station in data:
    # 遍历该充电站的所有连接
    for conn in station["Connections"]:
        total += conn["Quantity"]

print(total)  # 输出:5

方法3:pandas链式操作简化

可以把步骤合并成链式调用,更简洁:

import pandas as pd

total_quantity = (
    pd.read_json("chargingStations.json")
    .explode("Connections")
    .pipe(lambda df: pd.json_normalize(df["Connections"]))
    ["Quantity"]
    .sum()
)

print(total_quantity)  # 输出:5

问题原因分析

之前的代码中,df["Connections"]是一个Series,每个元素是一个列表。直接对这个Series调用pd.json_normalize,会把每个列表当成一个单独的对象处理,导致生成的DataFrame结构不符合预期,无法直接提取Quantity字段。而explode操作可以把列表中的每个元素拆分成单独的行,之后再标准化就能正确提取每个子字典中的字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 04:45:35