繁体   English   中英

从 Pandas 中的 JSON 数据框中提取某些键

[英]Extracting certain keys from a JSON dataframe in pandas

所以我有这个 JSON

{
  "data": [
    {
      "id": 2674,
      "timestamp": "2022-07-01",
      "vendor_name": "test",
      "npi_id": "1234567890",
      "trigger_description": "test",
      "echo_order": 0,
      "duration": "0",
      "image_url": "https://....",
      "name": "Banner Ad Name 1",
      "triggers": ["test "]
    },
    {
   ...

我读的是这样df = pd.read_json("./data/data.json", typ="frame")

输出是...

> python main.py
                                                data
0  {'id': 2674, 'timestamp': '2022-07-01', 'vendo...
1  {'id': 2675, 'timestamp': '2022-07-01', 'vendo...
2  {'id': 6789, 'timestamp': '2022-07-01', 'vendo...
3  {'id': 2321, 'timestamp': '2022-07-01', 'vendo...
4  {'id': 5678, 'timestamp': '2022-07-01', 'vendo...
5  {'id': 1234, 'timestamp': '2022-07-01', 'vendo...

我正在寻找从输出中提取某些列。 但对于我的生活,我无法弄清楚如何。 数据在作为列表的关键data内。

当您对数据框执行df.columns时,您只会得到Index(['data'], dtype='object')

我如何获取内部数据并提取我需要的内容

所以我设法做到了……但我不确定这是否是真正的 Pandas 方式。

df = pd.read_json("./data/data.json", typ="frame")

    attribute_values = []

    for item in df["data"]:

        data = {
            "id": item["id"],
            "timestamp": item["timestamp"],
            "npi_id": item["npi_id"],
        }

        row = [data["id"], data["timestamp"], data["npi_id"]]
        attribute_values.append(row)
df = pd.read_json("./data/data.json", typ="frame")

给了我以下内容:

data
0  {'id': 2674, 'timestamp': '2022-07-01', 'vendo...
1  {'id': 2675, 'timestamp': '2022-07-01', 'vendo...
2  {'id': 6789, 'timestamp': '2022-07-01', 'vendo...
3  {'id': 2321, 'timestamp': '2022-07-01', 'vendo...
4  {'id': 5678, 'timestamp': '2022-07-01', 'vendo...
5  {'id': 1234, 'timestamp': '2022-07-01', 'vendo...

然后使用

for item in df["data"]:

        data = {
            "id": item["id"],
            "timestamp": item["timestamp"],
            "npi_id": item["npi_id"],
        }

        row = [data["id"], data["timestamp"], data["npi_id"]]
        attribute_values.append(row)

给我

[[2674, '2022-07-01', '1003883562'], [2675, '2022-07-01', '1043283849'], [6789, '2022-07-01', '1043283849'], [2321, '2022-07-01', '1043283849'], [5678, '2022-07-01', '1043283849'], [1234, '2022-07-01', '1043283849']]

这只是数据集中的id timestamp npi_id

您可以使用.str

out = df['data'].str['id']
print(out)

0    2674
Name: data, dtype: int64

或者使用pd.json_normalize

import json
with open('data.json', 'r', encoding='utf-8') as f:
    data = json.loads(f.read())
df = pd.json_normalize(data['data'])
print(df)

     id   timestamp vendor_name      npi_id trigger_description  echo_order duration     image_url              name triggers
0  2674  2022-07-01        test  1234567890                test           0        0  https://....  Banner Ad Name 1  [test ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM