首页 > 解决方案 > 将 DataFrame 列转换为 json 列

问题描述

我有一个熊猫数据框,其中一列是 json 类型,但如下所示:列 {1:1,2:2,3:3}

但我希望这是真正的 json 格式,如列 {"1":1,"2":2,"3":3}

目前该列的数据类型是对象

标签: pythonjsonpandasdataframe

解决方案


这应该有效:

import ast
import json
import pandas


def convert_json(row: pandas.Series) -> pandas.Series:

    # Read the string as a python dictionary (literal_eval), then, turn the key into a string, then dump as a valid JSON string
    row["real_json"] = json.dumps({str(key): value for key, value in ast.literal_eval(row["my_json"]).items()})

    # Return the row
    return row


# Some test data
df = pandas.DataFrame([{"my_json": "{1:1,2:2,3:3}"} for _ in range(10)])

# Loop the rows and apply the function
df = df.apply(convert_json, axis=1)

输出:

print(df)
         my_json                 real_json
0  {1:1,2:2,3:3}  {"1": 1, "2": 2, "3": 3}
1  {1:1,2:2,3:3}  {"1": 1, "2": 2, "3": 3}
2  {1:1,2:2,3:3}  {"1": 1, "2": 2, "3": 3}
3  {1:1,2:2,3:3}  {"1": 1, "2": 2, "3": 3}
4  {1:1,2:2,3:3}  {"1": 1, "2": 2, "3": 3}
5  {1:1,2:2,3:3}  {"1": 1, "2": 2, "3": 3}
6  {1:1,2:2,3:3}  {"1": 1, "2": 2, "3": 3}
7  {1:1,2:2,3:3}  {"1": 1, "2": 2, "3": 3}
8  {1:1,2:2,3:3}  {"1": 1, "2": 2, "3": 3}
9  {1:1,2:2,3:3}  {"1": 1, "2": 2, "3": 3}

推荐阅读