我在資料框列中有一個 JSON:
x = '''{"sections":
[{
"id": "12ab",
"items": [
{"id": "34cd",
"isValid": true,
"questionaire": {"title": "blah blah", "question": "Date of Purchase"}
},
{"id": "56ef",
"isValid": true,
"questionaire": {"title": "something useless", "question": "Date of Billing"}
}
]
}],
"ignore": "yes"}'''
我想要 id、專案串列中的內部 id 以及來自問卷 json 的問題:
我能夠使用以下代碼提取資訊:
df_norm = json_normalize(json.loads(x)['sections'])
df_norm = df_norm[['id', 'items']]
df1 = (pd.concat({k: pd.DataFrame(v) for k, v in df_norm.pop('items').items()}).reset_index(level=1, drop=True))
df = df_norm.join(df1, rsuffix='_').reset_index(drop=True)
df['child_id'] = df.pop('id_')
df = df[['id', 'child_id', 'questionaire']]
df.questionaire = df.questionaire.fillna({i: {} for i in df.index})
idx = df.set_index(['id', 'child_id']).questionaire.index
result = pd.DataFrame(df.
set_index(['id', 'child_id']).
questionaire.values.tolist(),index=idx).reset_index()
result = result[['id','child_id','question']]
result
結果 DataFrame 看起來像這樣。您可以運行它來驗證:
| ID | child_id | 題 | |
|---|---|---|---|
| 0 | 12ab | 34cd | 購買日期 |
| 1 | 12ab | 56ef | 計費日期 |
我的問題是使用 Dataframe 進行這項作業,其中上面共享的 json 值本身就是一列。我實際輸入的內容如下所示:
| ID | 姓名 | 地點 | 展平 |
|---|---|---|---|
| 1 | xyz | 紐約 | 上面的 json 'x' |
當我必須為多個這樣的 JSON 作為列值執行此操作時,我無法將其重新系結。
我想要的最終結果 DataFrame 是:
| 萬事達 | 姓名 | 地點 | ID | child_id | 題 |
|---|---|---|---|---|---|
| 1 | xyz | 紐約 | 12ab | 34cd | 購買日期 |
| 1 | xyz | 紐約 | 12ab | 56ef | 計費日期 |
uj5u.com熱心網友回復:
想法是使用帶有索引值列flatten的字典理解,因此可以加入原始資料幀:iconcat
x = '''{"sections":
[{
"id": "12ab",
"items": [
{"id": "34cd",
"isValid": true,
"questionaire": {"title": "blah blah", "question": "Date of Purchase"}
},
{"id": "56ef",
"isValid": true,
"questionaire": {"title": "something useless", "question": "Date of Billing"}
}
]
}],
"ignore": "yes"}'''
df = pd.DataFrame({'id':['1','2'], 'name':['xyz', 'abc'],
'location':['new york', 'wien'], 'flatten':[x,x]})
#create default RangeIndex
df = df.reset_index(drop=True)
d = {i: pd.json_normalize(json.loads(x)['sections'],
'items', ['id'],
record_prefix='child_')[['id','child_id','child_questionaire.question']]
.rename(columns={'child_questionaire.question':'question'})
for i, x in df.pop('flatten').items()}
df_norm = df.rename(columns={'id':'Masterid'}).join(pd.concat(d).reset_index(level=1, drop=True))
print (df_norm)
Masterid name location id child_id question
0 1 xyz new york 12ab 34cd Date of Purchase
0 1 xyz new york 12ab 56ef Date of Billing
1 2 abc wien 12ab 34cd Date of Purchase
1 2 abc wien 12ab 56ef Date of Billing
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/455760.html
上一篇:使用R計算比率矩陣
