[英]Convert a three-level hierarchical data into a specific json format
我有一個三級分層數據集,如下所示:
pd.DataFrame({'level1': ['A', 'A', 'A', 'A', 'B'],
'level2': ['A1', 'A1', 'A2', 'A2', 'B1' ],
'level3': ['a', 'b', 'c', 'd', 'e'],
'value': [44, 125, 787, 99, 111],
'pctChg': [0.3, -0.9, -10.0, 12, -0.2]})
level1 level2 level3 value pctChg
0 A A1 a 44 0.3
1 A A1 b 125 -0.9
2 A A2 c 787 -10.0
3 A A2 d 99 12.0
4 B B1 e 111 -0.2
對於像A
這樣的特定 level1 類別,有像A1, A2
這樣的 level2 類別。 在二級之下,有許多三級類別。 例如,“a”和“b”在“A1”下,“c”和“d”在A2下。 這個數據只是一個例子。 對於每個組合,都有價值和百分比信息(與上個月相比的百分比變化)。
我需要將此數據轉換為嵌套的 json 數據。 它需要是如下格式:
{
name: “root”,
value: 1166,
pctChg: xx%,
children: [
{
name: 'A',
value: 956,
pctChg: 'xx%'',
children: [{
name: 'A1',
value: 169,
pctChg: 'xx%'',
children: [{name: 'a', value: 44, pctChg: '30%'},
{name:'b', value:125, pctChg: '-90%'},
{name:'c', value:787, pctChg: '-10%'}
]
}, .....]
},
.....…
]
}
我們還需要匯總一個級別下所有子級的值。 價值可以明顯增加。 一個棘手的部分是百分比。 我們可能不想簡單地匯總百分比。
這看起來是一項相當艱巨的任務。 不像一些簡單的嵌套 json 數據。 我不確定我該如何處理。 感謝有人可以提供幫助。 非常感謝。
第一步是將pctChg列重新格式化為百分比字符串:
df.pctChg = (df.pctChg * 100).astype(int).astype(str) + '%'
(我假設乘以 100公式)。
然后定義 2 個函數來計算第二級和第一級的子級:
def chld2(grp):
return grp.rename(columns={'level3': 'name'}).groupby('level2')\
.apply(lambda grp: pd.Series({'name': grp.iloc[0,1], 'value': grp.value.sum(),
'pctChg': 'xx%', 'children': grp[['name', 'value', 'pctChg']].to_dict('r') }))\
.to_dict('r')
def chld1(df):
return df.groupby('level1').apply(lambda grp: pd.Series({
'name': grp.iloc[0,0], 'value': grp.value.sum(), 'pctChg': 'xx%',
'children': chld2(grp)})).to_dict('r')
要生成結果,請運行:
pd.Series({'name': 'root', 'value': df.value.sum(), 'pctChg': 'xx%',
'children': chld1(df)}).to_json()
結果(手動添加縮進以提高可讀性)是:
{ "name":"root", "value":1166, "pctChg":"xx%",
"children":[
{ "name":"A", "value":1055, "pctChg":"xx%",
"children":[
{ "name":"A1", "value":169, "pctChg":"xx%",
"children":[
{"name":"a", "value":44, "pctChg":"30%"},
{"name":"b", "value":125, "pctChg":"-90%"}
]
},
{ "name":"A2", "value":886, "pctChg":"xx%",
"children":[
{"name":"c", "value":787, "pctChg":"-1000%"},
{"name":"d", "value":99, "pctChg":"1200%"}
]
}
]
},
{ "name":"B", "value":111, "pctChg":"xx%",
"children":[
{ "name":"B1", "value":111, "pctChg":"xx%",
"children":[
{"name":"e", "value":111, "pctChg":"-20%"}
]
}
]
}
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.