【发布时间】:2020-08-22 04:47:15
【问题描述】:
我是 pandas/Python 新手,想知道您能否帮助我解决以下问题。
考虑以下 csv 文件:
country,continent,year,productA,productB
NLD,Europe,2012,1000,500
NLD,Europe,2013,100,50
NLD,Europe,2014,150,40
NLD,Europe,2015,200,70
CAN,America,2012,30,40
CAN,America,2013,50,90
CAN,America,2014,200,2000
CAN,America,2015,20,30
JPN,Asia,2012,100,2000
JPN,Asia,2013,400,100
JPN,Asia,2014,300,3000
JPN,Asia,2015,400,370
我想将其重写为类似 JSON 的文件:
[
{
country: 'NLD',
continent: 'Europe',
productA: {
2012: '1000',
2013: '100',
2004: '150',
2005: '200',
},
productB: {
2012: '500',
2013: '50',
2004: '40',
2005: '70',
},
},
{
country: 'CAN',
continent: 'America',
productA: {
2012: '30',
2013: '50',
2004: '200',
2005: '20',
},
productB: {
2012: '40',
2013: '90',
2004: '200',
2005: '30',
},
},
{
country: 'JPN',
continent: 'Asia',
productA: {
2012: '100',
2013: '400',
2004: '300',
2005: '400',
},
productB: {
2012: '2000',
2013: '100',
2004: '3000',
2005: '370',
},
},
]
这个question 类似,但由于我的知识有限,我无法根据自己的需要调整答案。通过使用上述问题的答案,我可以写这个sn-p:
json = (df.groupby(['country','continent'], as_index=False)
.apply(lambda x: dict(zip(x.year,x.productA)))
.reset_index()
.rename(columns={0:'productA'})
.to_json(orient='records'))
,结果是
[
{
country: 'NLD',
continent: 'Europe',
productA: {
2012: '1000',
2013: '100',
2004: '150',
2005: '200',
},
},
{
country: 'CAN',
continent: 'America',
productA: {
2012: '30',
2013: '50',
2004: '200',
2005: '20',
},
},
{
country: 'JPN',
continent: 'Asia',
productA: {
2012: '100',
2013: '400',
2004: '300',
2005: '400',
},
},
]
如果您能帮助我达到理想的输出(包括 productB)并建议我可以用来提高我使用 Pandas 处理数据的技能的资源,我将不胜感激。
谢谢!
【问题讨论】: