【问题标题】:Convert JSON data in data frame Python [duplicate]在数据框Python中转换JSON数据[重复]
【发布时间】:2020-12-02 18:42:43
【问题描述】:

我是编程语言的初学者,非常感谢您的帮助和支持。

这是DataFrame,一列的数据是JSON类型?数据。

ID, Name, Information
1234, xxxx, '{'age': 25, 'gender': 'male'}'
2234, yyyy, '{'age': 34, 'gender': 'female'}'
3234, zzzz, '{'age': 55, 'gender': 'male'}'

我想将这个 DataFrame 隐藏如下。

ID, Name, age, gender
1234, xxxx, 25, male
2234, yyyy, 34, female
3234, zzzz, 55, male

我发现ast.literal_eval()可以将str转为dict类型,但是我不知道怎么写这个问题的代码。

您能否举一些可以解决此问题的代码示例?

【问题讨论】:

    标签: python json dataframe json-normalize


    【解决方案1】:

    给定test.csv

    ID,Name,Information
    1234,xxxx,"{'age': 25, 'gender': 'male'}"
    2234,yyyy,"{'age': 34, 'gender': 'female'}"
    3234,zzzz,"{'age': 55, 'gender': 'male'}"
    
    • 使用pd.read_csv 读取文件并将converters 参数与ast.literal_eval 一起使用,这会将Information 列中的数据从str 类型转换为dict 类型。
    • 使用pd.json_normalize 解压缩dict,其中键作为列标题,值在行中
    • .join 带有df 的规范化列
    • .dropInformation 专栏
    import pandas as pd
    from ast import literal_eval
    
    df = pd.read_csv('test.csv', converters={'Information': literal_eval})
    
    df = df.join(pd.json_normalize(df.Information))
    
    df.drop(columns=['Information'], inplace=True)
    
    # display(df)
         ID  Name  age  gender
    0  1234  xxxx   25    male
    1  2234  yyyy   34  female
    2  3234  zzzz   55    male
    

    如果数据不是来自 csv 文件

    import pandas as pd
    from ast import literal_eval
    
    data = {'ID': [1234, 2234, 3234],
            'Name': ['xxxx', 'yyyy', 'zzzz'],
            'Information': ["{'age': 25, 'gender': 'male'}", "{'age': 34, 'gender': 'female'}", "{'age': 55, 'gender': 'male'}"]}
    
    df = pd.DataFrame(data)
    
    # apply literal_eval to Information
    df.Information = df.Information.apply(literal_eval)
    
    # normalize the Information column and join to df
    df = df.join(pd.json_normalize(df.Information))
    
    # drop the Information column
    df.drop(columns=['Information'], inplace=True)
    

    【讨论】:

    • 嗨,Tranton,感谢您提供详细信息的回答。这些细节帮助我更轻松地学习 python。问题以您首先发布的 CSV 方式解决。谢谢。
    【解决方案2】:
    1. 如果第三列是JSON字符串,'无效,应该是",所以我们需要解决这个问题。
    2. 如果第三列是pythondict的字符串表示,可以使用eval进行转换。

    拆分dict类型的第三列并合并到原始DataFrame的代码示例:

    data = [
      [1234, 'xxxx', "{'age': 25, 'gender': 'male'}"],
      [2234, 'yyyy', "{'age': 34, 'gender': 'female'}"],
      [3234, 'zzzz', "{'age': 55, 'gender': 'male'}"],
    ]
    
    df = pd.DataFrame().from_dict(data)
    
    df[2] = df[2].apply(lambda x: json.loads(x.replace("'", '"'))) # fix the data and convert to dict
    merged = pd.concat([df[[0, 1]], df[2].apply(pd.Series)], axis=1)
    

    【讨论】:

    • 您好 Kassian,感谢您的回答。我也会根据您的建议尝试一下。
    猜你喜欢
    • 2019-09-12
    • 2020-05-29
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 2023-03-27
    • 2017-10-31
    • 1970-01-01
    相关资源
    最近更新 更多