【问题标题】:DataFrame to nested JSON with Python?使用 Python 到嵌套 JSON 的 DataFrame?
【发布时间】:2019-10-25 07:43:57
【问题描述】:

我正在尝试从 SQL 中提取数据并将其转换为 JSON 文件。

我还尝试了各种网站上提到的其他“技术”,但没有任何成功。

所以基本上我在下面的陈述之后“卡住”了

j = (df.groupby(['SectionCode'])
     .apply(lambda x: x[['Barcode', 'BrandCode', 'PurchaseRate', 'SalesRate', 'unit','Item']].to_dict('r'))
     .reset_index()
     .rename(columns={0: 'Products'})
     .to_json(r'D:\DataToFirbaseWithPython\Export_DataFrame.json'))

print(j)

需要这种json格式。

"SectionsWithItem": { #Root_Nose_In_Firebase
  "0001": { #SectionCode
    "Products": {
            "018123": { #Barcode
        "Barcode": "018123",
                "BrandCode": "1004",
                "PurchaseRate": 105.0,
                "SalesRate": 125.0,
                "Units": "Piece",
                "name": "Shahi Delux Mouth Freshener"
            },
            "0039217": { #Barcode
        "Barcode": "0039217",
                "BrandCode": "0814",
                "PurchaseRate": 140.0,
                "SalesRate": 160.0,
                "Units": "Piece",
                "name": "Maizban Gota Pan Masala Medium Jar"
            }
        }
    },
    "0002": { #SectionCode
    "Products": {
            "03905": { #Barcode
        "Barcode": "03905",
                "BrandCode": "0189",
                "PurchaseRate": 15.4,
                "SalesRate": 17.0,
                "Units": "Piece",
                "name": "Peek Freans Rio Chocolate Half Roll"
            },
            "0003910": { #Barcode
        "Barcode": "0003910",
                "BrandCode": "0189",
                "PurchaseRate": 110.32,
                "SalesRate": 120.0,
                "Units": "Piece",
                "name": "Peek Freans Gluco Ticky Pack Box"
            }
        }
    }
}

我的数据框

Barcode,Item,SalesRate,PurchaseRate,unit,BrandCode,SectionCode
0005575,Broom Soft A Quality,100.0,80.0,,2037,0045
0005850,Safa Tomato Paste 800g,340.0,275.0,800g,1004,0009
0005921,Dettol Liquid 1Ltr,800.0,719.99,1Ltr,0475,0045

【问题讨论】:

    标签: python json sql-server firebase dataframe


    【解决方案1】:

    按条形码分组也应该有助于像所需输出那样进行索引。

    import pandas as pd
    import json
    
    df = pd.read_csv('stac1 - Sheet1.csv', dtype=str) #made dataframe with provided data
    
    j = (df.groupby(['SectionCode', 'Barcode'])
         .apply(lambda x: x[['Barcode', 'BrandCode', 'PurchaseRate', 'SalesRate','unit','Item']].to_dict('r'))
         .reset_index()
         .rename(columns={0: 'Products'})
         .to_json(r'Export_DataFrame.json'))
    
    with open('Export_DataFrame.json') as f:
        data = json.load(f)
    
    print(data)
    

    希望这可以帮助您找到正确的方向!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-10
      • 2020-07-16
      • 1970-01-01
      • 2020-02-25
      • 2018-05-09
      • 2019-08-20
      • 2018-09-01
      • 2020-07-12
      相关资源
      最近更新 更多