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_records
、from_json
或json_normalize
都可以提供我想要的大部分内容,但列表只在一列中:
t_df = pd.json_normalize(data)
t_df
输出:
ticket_id | customer_id | created_at | custom_fields | group_id | |
---|---|---|---|---|---|
0 | 4 | 8 | 2022-05-01 | [{'id': 15, 'value': 'website'}, {'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')
这会产生一条正确的记录,我可以将其附加到主数据帧:
ticket_id | customer_id | created_at | group_id | 15 | 16 | 23 | |
---|---|---|---|---|---|---|---|
0 | 4 | 8 | 2022-05-01 | 42 | website | broken | None |
我担心的是,我需要对大约25000条记录执行此操作,而这似乎既慢又脆(容易损坏).