gpt4 book ai didi

python - 将 pandas multiindex 系列转换为 Json python

转载 作者:行者123 更新时间:2023-12-01 01:30:25 24 4
gpt4 key购买 nike

嗨,我有两个类似于下面的 pandas 系列

盈亏

           Product Name      Price
Company A Orange 3000
Company B Apple 2000
Grapes 1000

           Product Name      Price
Company A Orange 100
Company B Apple 100
Grapes 10

我想将 pandas 系列转换为以下 JSON 格式

{'PnL':{'Company A':{'productName':'Orange','price':3000},
'Company B':[{'productName':'Apple','price':2000},
{'productName':'Grapes','price':1000}]
},
'Tax':{'Company A':{'productName':'Orange','price':100},
'Company B':[{'productName':'Apple','price':100},
{'productName':'Grapes','price':10}]
}
}

我尝试使用下面的代码

convertedJson = json.dumps([{'company': k[0], 'productName':k[1],'price': v} for k,v in df.items()])

但我无法形成我想要生成的 JSON。谢谢您的帮助

最佳答案

您可以使用concat将 DaatFrame 连接在一起,然后 groupbyto_dict预期输出:

df = pd.concat([s1, s2], keys=('PnL','Tax')).reset_index()
df.columns = ['type','company','productName','price']
print (df)
type company productName price
0 PnL Company A Orange 3000
1 PnL Company B Apple 2000
2 PnL Company B Grapes 1000
3 Tax Company A Orange 3000
4 Tax Company B Apple 2000
5 Tax Company B Grapes 1000

d = (df.groupby(['type','company'])['productName','price']
.apply(lambda x: x.to_dict('r'))
.reset_index(name='data')
.groupby('type')['company','data']
.apply(lambda x: x.set_index('company')['data'].to_dict())
.to_json()
)
<小时/>
print (d)

{
"PnL": {
"Company A": [{
"productName": "Orange",
"price": 3000
}],
"Company B": [{
"productName": "Apple",
"price": 2000
}, {
"productName": "Grapes",
"price": 1000
}]
},
"Tax": {
"Company A": [{
"productName": "Orange",
"price": 3000
}],
"Company B": [{
"productName": "Apple",
"price": 2000
}, {
"productName": "Grapes",
"price": 1000
}]
}
}

关于python - 将 pandas multiindex 系列转换为 Json python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52923685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com