【问题标题】:Flatten nested JSON and concatenate to dataframe using pandas使用 pandas 展平嵌套 JSON 并连接到数据框
【发布时间】:2020-11-24 21:21:27
【问题描述】:

我在网上搜索了很多类似的主题,但我还没有找到解决方案。

我的 pandas 数据框如下所示:

index    FOR
0        [{'id': '2766', 'name': '0803 Computer Softwar...
1        [{'id': '2766', 'name': '0803 Computer Softwar...
2        [{'id': '2766', 'name': '0803 Computer Softwar...
3        [{'id': '2766', 'name': '0803 Computer Softwar...
4        [{'id': '2766', 'name': '0803 Computer Softwar...

我想将所有 4 行展平为如下数据框,而下面只是第一行的结果:

index   id      name
0       2766    0803 Computer Software

我找到了类似的解决方案here。不幸的是,我得到了一个“TypeError”,如下所示: TypeError: JSON 对象必须是 str、bytes 或 bytearray,而不是 'list'

我的代码是:

dfs = []
for i in test['FOR']:
    data = json.loads(i)
    dfx = pd.json_normalize(data)
    dfs.append(dfx)   

df = pd.concat(dfs).reset_index(inplace = True)
print(df)

有人可以在这里帮助我吗? 非常感谢!

【问题讨论】:

    标签: python json pandas normalize


    【解决方案1】:

    尝试使用来自ast 标准库的literal_eval

    from ast import literal_eval
    
    
    df_flattened = pd.json_normalize(df['FOR'].map(literal_eval))
    

    然后删除重复项。

    print(df_flattened.drop_duplicates())
    
         id                    name
    0  2766  0803 Computer Software
    

    【讨论】:

    • 感谢您的帮助。不幸的是,我收到以下错误: ValueError: malformed node or string: [{'id': '2766', 'name': '0803 Computer Software'}]
    • @Chen 更新您的示例以模仿您的问题 - 我没有看到 json 对象列表。
    • 很抱歉我从 Colab 复制了表格,因此它可能会丢失一些东西。我是 CoLab 的新手。但是如果我打印: type(test['FOR'][0]) 它确实显示了一个列表。对于造成的混乱,我深表歉意。
    • @Chen 每个列表中有什么,只是一个 json 对象还是很多?
    • 如果我理解正确的话,有两个:[{"id": "2766", "name": "0803 Computer Software"}]
    【解决方案2】:

    几周没碰相关作品后, 我遇到了另一个类似的情况, 我想到目前为止我已经为这个案例找到了解决方案。 请随时纠正我或提供任何其他想法。 我非常感谢所有的帮助和慷慨的支持!

    chuck = []
    
    for i in range(len(test)):
        chuck.append(json_normalize(test.iloc[i,:]['FOR']))
    
    test_df = pd.concat(chuck)
    

    然后删除 test_df 的重复列

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 2020-09-27
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2021-05-14
      • 2020-03-11
      • 2021-04-27
      • 1970-01-01
      相关资源
      最近更新 更多