[英]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_records
、 from_json
或json_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.