python - 如何从 Pandas 的嵌套字典中获取特定的键值?

标签 python pandas list dictionary nested

我有一个嵌套的 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,
    }
]

如您所见,此 JSON 文件的列表由两个字典组成,每个字典都包含另一个列表(=“连接”),该列表至少包含一个字典。在此 JSON 文件的每个字典中,我想选择所有名为“Quantity”的键来对其值进行计算(因此在上面的示例代码中,我想计算总共有 5 个数量)。

使用下面的代码,我在 Pandas 中创建了一个简单的数据框来进行此计算:

import json
import pandas as pd

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

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

print(dfConnections)

结果是: enter image description here

理想情况下,我想从每个字典中获取“Quantity”键,以便我可以制作这样的数据框(其中每个项目都有自己的行): enter image description here

但是,我不确定这是否是进行计算的最佳方法。我尝试通过输入 dfConnections = dfConnections.get("Quantity") 来获取“Quantity”键的每个值,但这会导致 None。那么:如何获取每个字典中每个“Quantity”键的值来进行计算?

最佳答案

如果data从你的问题中解析Json数据,你可以这样做:

df = pd.DataFrame(
    [
        {
            i: sum(dd["Quantity"] for dd in d["Connections"])
            for i, d in enumerate(data)
        }
    ]
)
print(df)

打印:

<表类=“s-表”> <标题> 0 1 <正文> 0 2 3

关于python - 如何从 Pandas 的嵌套字典中获取特定的键值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74089340/

相关文章:

python - Python 中多条目的蒙特卡罗模拟

python - 如何检查一个序列是严格单调的还是有一个转折点两边都是严格单调的?

list - 在列表列表中查找形状

java - 从抽象类返回类型化列表变为非类型化/原始列表

python - 在Python 3中判断一个数字是否是平方数的最快方法是什么

python - 通过 Fit Models 训练模型时如何修复 "Unknown label type: 'unknown'"

python - 向数据帧添加索引级别

python: getfilesystemencoding() 在 shell 和 wsgi 中返回不同的值

python - 拟合中的神经网络 - 乳腺癌数据集

python - Pandas 不识别 csv 列