繁体   English   中英

以理智的方式将字典列表转换为Dataframe

[英]Converting list of dictionaries into Dataframe in sane way

zendesk api 将字段作为字典列表返回,但每个列表都是一条记录。 我想知道是否有更好的方法将其全部转换为数据框。 如果它是字典字典,那么json_normalize会毫无问题地处理它。

警告:并非所有记录都具有相同的字段 ID

样本数据:

data = [{
  "ticket_id": 4,
  "customer_id": 8,
  "created_at": "2022-05-01",
  "custom_fields": [
    {
      "id": 15,
      "value": "website"
    },
    {
      "id": 16,
      "value": "broken"
    },
    {
      "id": 23,
      "value": None
    },
  ],
  'group_id': 42
}]

运行任何形式的 Dataframe、 from_recordsfrom_jsonjson_normalize提供我想要的大部分内容,但列表在一列中:

t_df = pd.json_normalize(data)
t_df

输出:

票号 客户ID created_at 自定义字段 group_id
0 4 8 2022-05-01 [{'id': 15, 'value': '网站'}, {'id': 16, 'v... 42

我目前的,可能是不明智的解决方案是:

t_df = pd.DataFrame(sample_df.at[0, 'custom_fields']).T.reset_index(drop=True)
t_df.rename(columns=t_df.iloc[0], inplace=True)
t_df.drop(0, inplace=True)
t_df.reset_index(drop=True, inplace=True)
pd.merge(left=sample_df, left_index=True,
         right=t_df, right_index=True).drop(columns='custom_fields')

这会产生一个正确的记录,我可以将其附加到主数据框:

票号 客户ID created_at group_id 15 16 23
0 4 8 2022-05-01 42 网站 破碎的 没有任何

我担心我需要对约 25,000 条记录执行此操作,这似乎既缓慢又脆弱(容易损坏)。

您应该先处理数据/字典,然后再用它构造一个 DataFrame。 它将使您的生活更轻松,并且比尝试使用pandas操作数据(即在创建 DataFrame 之后)更快。

import pandas as pd

data = [{
  "ticket_id": 4,
  "customer_id": 8,
  "created_at": "2022-05-01",
  "custom_fields": [
    {
      "id": 15,
      "value": "website"
    },
    {
      "id": 16,
      "value": "broken"
    },
    {
      "id": 23,
      "value": None
    },
  ],
  'group_id': 42
}]

custom_fields = data[0].pop('custom_fields')
data[0].update({rec['id']: rec['value'] for rec in custom_fields})

t_df = pd.DataFrame(data)

输出:

>>> t_df 

   ticket_id  customer_id  created_at  group_id       15      16    23
0          4            8  2022-05-01        42  website  broken  None

看起来熊猫不会自动确定哪些字段是“元数据”,哪些是“记录”-->如果您的数据是固定的,我建议对以下内容进行硬编码:

>>> t_df = pd.json_normalize(
...     data,
...     meta=["ticket_id", "customer_id", "created_at", "group_id"],
...     record_path=["custom_fields"]
... )

   id    value ticket_id customer_id  created_at group_id
0  15  website         4           8  2022-05-01       42
1  16   broken         4           8  2022-05-01       42
2  23     None         4           8  2022-05-01       42

文档: https ://pandas.pydata.org/docs/reference/api/pandas.json_normalize.html

import pandas as pd
data = [{
  "ticket_id": 4,
  "customer_id": 8,
  "created_at": "2022-05-01",
  "custom_fields": [
    {
      "id": 15,
      "value": "website"
    },
    {
      "id": 16,
      "value": "broken"
    },
    {
      "id": 23,
      "value": None
    },
  ],
  'group_id': 42
}]
df = pd.DataFrame(data)
for index in df.index:
    for i in df.loc[index,'custom_fields']:
        df.loc[index,i['id']] = i['value']
df.drop(columns = 'custom_fields',inplace = True)
df

暂无
暂无

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

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