【问题标题】:Build JSON object from pandas dataframe从 pandas 数据框构建 JSON 对象
【发布时间】:2019-01-16 07:08:28
【问题描述】:

我正在尝试格式化熊猫数据框:

> year mileage model    manufacturer    power fuel_type price
> 0 2011    184000  c-klasa Mercedes-Benz   161 diesel  114340
> 1 2013    102000  v40 Volvo   130 diesel  80511
> 2 2014    191000  scenic  Renault 85  diesel  57613
> 3 1996    210000  vectra  Opel    85  benzin  6278
> 4 2005    258000  tucson  Hyundai 83  diesel  41363
> 5 2007    325000  astra   Opel    74  diesel  26590
> 6 2002    200000  megane  Renault 79  plin    16988
> 7 2011    191000  touran  VW  77  diesel  62783
> 8 2007    210000  118 BMW 105 diesel  44318
> 9 2012    104000  3   Mazda   85  diesel  63522
> 10    2011    68000   c3  Citroen 54  benzin  44318
> 11    1993    200000  ax  Citroen 37  diesel  43467
> 12    2011    142000  twingo  Renault 55  benzin  28068
> 13    2005    280000  320 BMW 120 diesel  28068

输出以满足 JSON 对象要求。 这是我的代码:

for model, car in carsDF.groupby('manufacturer'):
    print("{\"",model,":\"[\"",'","'.join(car['model'].unique()),"\"]},") 

产生:

> {" Alfa Romeo
> :"["156","159","146","147","giulietta","gt","33","mito","166","145","brera","sprint","spider","155","ostalo
> "]}, {" Aston Martin :"[" vantage "]},...

除了每次我使用转义字符“\”时显示的空格外,其他都可以。

如何在没有它们的情况下创建 JSON 对象? 有没有更好的方法来为这种情况生成 JSON 对象?

【问题讨论】:

  • 可以添加一些示例数据吗?
  • 我已经添加了..

标签: python json python-3.x pandas dictionary


【解决方案1】:

我相信您需要通过unique 创建Series by SeriesGroupBy.unique 值,然后通过Series.to_json 转换为json:

j = carsDF.groupby('manufacturer')['model'].unique().to_json()
print (j)

{
    "BMW": ["118", "320"],
    "Citroen": ["c3", "ax"],
    "Hyundai": ["tucson"],
    "Mazda": ["3"],
    "Mercedes-Benz": ["c-klasa"],
    "Opel": ["vectra", "astra"],
    "Renault": ["scenic", "megane", "twingo"],
    "VW": ["touran"],
    "Volvo": ["v40"]
}

如果想要每个 json 单独的解决方案是创建 dictionaries 并转换为 jsons:

import json

for model, car in carsDF.groupby('manufacturer'):
    print (json.dumps({model: car['model'].unique().tolist()}))

{"BMW": ["118", "320"]}
{"Citroen": ["c3", "ax"]}
{"Hyundai": ["tucson"]}
{"Mazda": ["3"]}
{"Mercedes-Benz": ["c-klasa"]}
{"Opel": ["vectra", "astra"]}
{"Renault": ["scenic", "megane", "twingo"]}
{"VW": ["touran"]}
{"Volvo": ["v40"]}

【讨论】:

猜你喜欢
  • 2014-01-05
  • 2019-10-22
  • 2021-01-09
  • 2018-12-09
  • 1970-01-01
  • 2022-11-13
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
相关资源
最近更新 更多