【问题标题】:Convert DataFrame to JSON in python在python中将DataFrame转换为JSON
【发布时间】:2022-01-12 17:10:06
【问题描述】:

我有一个数据框,我想通过选择列将其转换为 json 格式。而且由于我的台词很多,我不能手工做所有事情

我有一个看起来像这样的数据框:

 Cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4', np.nan, 'Ford', 'Audi A1'],
    'Price': [22000,25000,27000,35000, 29000, 27000, 35000],
    'Liscence Plate': ['ABC 123', 'XYZ 789', 'CBA 321', 'ZYX 987', 'DEF 456', 'DEF 466', 'ABC 123']}

df = pd.DataFrame(Cars,columns= ['Brand', 'Price', 'Liscence Plate'])


            Brand  Price Liscence Plate
0  Honda Civic     22000  ABC 123
1  Toyota Corolla  25000  XYZ 789
2  Ford Focus      27000  CBA 321
3  Audi A4         35000  ZYX 987
4  NaN             29000  DEF 456
5  Ford            27000  DEF 466
6  Audi A1         35000  ABC 123

我必须转换成这个:

data = {"form": [
             {"Liscence Plate": "ABC 123",
              "Brand": ["Honda Civic", "Audi A1"
],
              "Price": ["22000", "35000"]},
{"Liscence Plate": "XYZ 789",
              "Brand": ["Toyota Corolla",
],
              "Price": ["25000"]},
{"Liscence Plate": "CBA 321",
              "Brand": ["Ford Focus",
],
              "Price": ["27000"]},
{"Liscence Plate": "ZYX 987",
              "Brand": ["Audi A4",
],
              "Price": ["35000"]},
{"Liscence Plate": "DEF 456",
              "Brand": ["NaN", "Ford"
],
              "Price": ["29000", "27000"]}

【问题讨论】:

    标签: python json dataframe


    【解决方案1】:

    所以你想要这个?

    df.to_json(orient='records')
    

    输出:

    [{
        "Brand": "Honda Civic",
        "Price": 22000,
        "Liscence Plate": "ABC 123"
    }, {
        "Brand": "Toyota Corolla",
        "Price": 25000,
        "Liscence Plate": "XYZ 789"
    }, {
        "Brand": "Ford Focus",
        "Price": 27000,
        "Liscence Plate": "CBA 321"
    }, {
        "Brand": "Audi A4",
        "Price": 35000,
        "Liscence Plate": "ZYX 987"
    }, {
        "Brand": null,
        "Price": 29000,
        "Liscence Plate": "DEF 456"
    }]
    

    编辑:

    df = df.groupby('Liscence Plate').agg({'Brand': lambda x: list(x), 'Price': lambda x: list(x)}).reset_index()
    df.to_json(orient='records')
    
    [{
        "Liscence Plate": "ABC 123",
        "Brand": ["Honda Civic"],
        "Price": [22000]
    }, {
        "Liscence Plate": "CBA 321",
        "Brand": ["Ford Focus"],
        "Price": [27000]
    }, {
        "Liscence Plate": "DEF 456",
        "Brand": [null, "Ford F-150"],
        "Price": [29000, 33000]
    }, {
        "Liscence Plate": "XYZ 789",
        "Brand": ["Toyota Corolla"],
        "Price": [25000]
    }, {
        "Liscence Plate": "ZYX 987",
        "Brand": ["Audi A4"],
        "Price": [35000]
    }]
    

    在开头添加自定义键:

    '{\"form\": ' + df.to_json(orient='records') + '}'
    

    \" 转义了 ",因此表单被引用。

    {
        "form": [{
            "Liscence Plate": "ABC 123",
            "Brand": ["Honda Civic"],
            "Price": [22000]
        }, {
            "Liscence Plate": "CBA 321",
            "Brand": ["Ford Focus"],
            "Price": [27000]
        }, {
            "Liscence Plate": "DEF 456",
            "Brand": [null, "Ford F-150"],
            "Price": [29000, 33000]
        }, {
            "Liscence Plate": "XYZ 789",
            "Brand": ["Toyota Corolla"],
            "Price": [25000]
        }, {
            "Liscence Plate": "ZYX 987",
            "Brand": ["Audi A4"],
            "Price": [35000]
        }]
    }
    

    【讨论】:

    • @Mauris 由于“form”是整个数组的键,所以只需将其添加到开头即可。查看修改。
    【解决方案2】:

    看看.to_json() function。它将允许您轻松地将 DataFrame 转换为 json。您可以通过提供 orient 参数来更改 json 的架构。

    这可以很好地工作,但它不会为您提供品牌和价格键的列表。如果您想要更大的灵活性,您可以先使用具有相同 orient 参数的 .to_dict() 函数,进行更改,然后使用 json.dump() 转换为 json。

    编辑: 根据您的编辑,我认为您想先按车牌分组?在这种情况下,您可以这样做:

    df.groupby('Liscence Plate').agg(list).reset_index().to_json('records')
    

    聚合到列表并转换为 json。

    【讨论】:

    • 您好,是的,我检查了这些功能,但不允许转换为我想要的格式,例如特定位置的特定列
    • 导出的列顺序应与您的数据框相同,因此您可以在导出为 JSON 之前重新排序您的数据框like explained here。或者使用 .to_dict() 函数,然后使用 for 循环手动进行更改。
    • 我更新了我的问题和预期输出
    • 检查更新的答案
    【解决方案3】:

    使用pandas.DataFrame.iterrows 并“手动”构建结果。

    data = {'form' : [
                {k:[str(s[k])] if t == list else str(s[k])
                    for k, t in (("Liscence Plate", str), ("Brand", list), ("Price", list))}
                for _, s in df.iterrows()]
           }
    
    >>> data
    {'form': [
        {'Brand': ['Honda Civic'], 'Liscence Plate': 'ABC 123', 'Price': ['22000']},
        {'Brand': ['Toyota Corolla'], 'Liscence Plate': 'XYZ 789', 'Price': ['25000']},
        {'Brand': ['Ford Focus'], 'Liscence Plate': 'CBA 321', 'Price': ['27000']},
        {'Brand': ['Audi A4'], 'Liscence Plate': 'ZYX 987', 'Price': ['35000']},
        {'Brand': ['nan'], 'Liscence Plate': 'DEF 456', 'Price': ['29000']}
        ]
    }
    

    这与您正在寻找的非常接近。

    【讨论】:

    • 然后按照@Jan 命题 1/ 按 Liscence 板分组,2/导出为 dict 并在 dict 上循环以重新格式化。但是在分组之后,您还可以在导出为 dict 之前在数据框内重新格式化:更漂亮,更快
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 2019-05-19
    • 2020-04-12
    • 1970-01-01
    • 2017-04-13
    • 2021-03-29
    相关资源
    最近更新 更多