【问题标题】:Convert Python Pandas Dataframe to nested JSON formate将 Python Pandas Dataframe 转换为嵌套的 JSON 格式
【发布时间】:2021-12-29 00:13:48
【问题描述】:

我的数据来自这样的数据库:

Account Name Address1 State Zip Loantype expiry
100 Sam Street 5 NY NY001 E 2019
100 Sam Street 5 NY NY001 T 2020
100 Sam Street 10 NJ NJ001 E 2019
100 Sam Street 10 NJ NJ001 T 2020
101 John Street 1 CA CA001 E 2019
101 Joh Street 1 CA CA001 T 2020

我需要使用 python pandas 将上述数据转换为以下 json 格式。 我正在尝试 df.to_json(orient = 'index') 但它没有创建如下嵌套的甲酸盐。 有什么建议吗?

{
results: [
    {
        account:100,
        Name: Sam,
        LoanDetails : [
            {
                Address1: Street 5,
                State : NY,
                ZIP: NY0001,
                LoanList : [
                    {
                        Loantype: E,
                        expiry: 2012
                    }
                    {
                        Loantype: T,
                        expiry: 2020
                    }
                ]
            }
            {
                Address1: Street 10,
                State: NJ,
                ZIP: Nj0001,
                LoanList: [
                    {
                        Loantype: E,
                        expiry: 2019
                    }
                    {
                        Loantype: T,
                        expiry: 2020
                    }
                ]
            }
    }
    {
        account:100,
        Name: John,
        LoanDetails : 
            {
                Address1: Street 1,
                State : CA,
                ZIP: CA0001,
                LoanList : [
                    {
                        Loantype: E,
                        expiry: 2012
                    }
                    {
                        Loantype: T,
                        expiry: 2020
                    }
                ]
            }
    }
]
}

【问题讨论】:

    标签: python json pandas dataframe to-json


    【解决方案1】:

    我在下面尝试过,它成功了:

    import pandas as pd
    import json
    df = pd.DataFrame({'account':['100','100','100','100','101'],
                        'name':['sam','sam','sam','sam','john'],
                        'address1':['street 5','street 5','street 10','street 10','street 1'],
                        'state':['ny','ny','nj','nj','ca'],
                        'zip':['ny0001','ny0001','nj0001','nj0001','CA001'],
                        'loantype':['e','t','e','t','e'],
                       'expiry':[2019,2020,2019,2020,2019]
                       })
    
    
    k = df.groupby(['account','name','address1','state']).apply(lambda x:x[['loantype','expiry']].to_dict('records')).reset_index().rename(columns={0:'Loanlist'})#.to_json(orient = 'records')
    
    j = k.groupby(['account','name',]).apply(lambda x:x[['address1','state','Loanlist']].to_dict('records')).reset_index().rename(columns={0:'Loandetails'}).to_json(orient = 'records')
    
    print(j)
    

    【讨论】:

      【解决方案2】:

      这只是帮助您获得输出。可能有替代方法。

      a = {}
      for i in df.index:
          a[i]={}
          a[i]["LoanDetails"] = {}
          a[i]["LoanList"] = {}
          for col in df:
              if col in (["Account","Name"]):
                  a[i][col] = df[col].iloc[i]
              if col in (["Address1","State","Zip"]):
                  a[i]["LoanDetails"][col] = df[col].iloc[i]
              if col in (["Loantype","expiry"]):
                  a[i]["LoanList"][col] = df[col].iloc[i]
      b ={}
      b["Result"] =[]
      for i,v in a.items():
          b["Result"].append(v)
      

      【讨论】:

        猜你喜欢
        • 2019-06-09
        • 1970-01-01
        • 2014-06-27
        • 1970-01-01
        • 2021-03-07
        • 2017-01-08
        • 2020-09-29
        • 1970-01-01
        • 2021-12-09
        相关资源
        最近更新 更多