简体   繁体   English

将 DataFrame 列转换为 json 列

[英]Convert DataFrame column to json column

I have a pandas dataframe where one of the column is of json type but it is like below: column {1:1,2:2,3:3}我有一个 pandas dataframe 其中一列是 json 类型,但它如下所示:列 {1:1,2:2,3:3}

But i would want this to be in real json format like column {"1":1,"2":2,"3":3}但我希望这是真正的 json 格式,如列 {"1":1,"2":2,"3":3}

Currently the data type of the column is object目前该列的数据类型为 object

This should work:这应该有效:

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)

Output: Output:

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM