【问题标题】:Convert csv file into nested JSON-like file using pandas使用 pandas 将 csv 文件转换为类似 JSON 的嵌套文件
【发布时间】: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 处理数据的技能的资源,我将不胜感激。

谢谢!

【问题讨论】:

    标签: python json pandas nested


    【解决方案1】:

    请注意,pd.df_to_dict() 几乎可以满足您的要求(即使方向正确 - 请参阅 the documentation 了解其他选项。要获取国家/地区元组,只需循环

    dictlist=[]
    for i, j in df.groupby(['country', 'continent'):
        thedict =  j.to_dict()
        thedict["country"]= i[0]
        thedict["continent"] = i[1]
        dictlist.append(thedict)
    

    我很确定这方面的一些小变化会达到你想要的效果。

    【讨论】:

    • 嗨,伊戈尔——感谢您的留言。不幸的是,您提供的代码不足以让我达到理想的输出。我编辑了我的问题,以展示我到目前为止所取得的成就。也许你或其他人可以帮我修改我写的代码sn-p。
    猜你喜欢
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 2021-08-26
    • 2019-02-13
    • 2020-03-07
    • 2017-06-10
    相关资源
    最近更新 更多