展平嵌套JSON并使用pandas连接到数据帧

2024-10-02 10:33:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的熊猫数据框如下所示:

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)

有人能帮我吗? 多谢各位


Tags: 数据nameidjsondffordataindex
2条回答

经过几周不接触相关工作, 我遇到了另一个类似的情况,并且 我想到目前为止我已经找到了解决这个问题的办法。 请随时纠正我或提供任何其他想法。 我真的很感激所有的帮助和慷慨的支持

chuck = []

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

test_df = pd.concat(chuck)

然后删除测试的重复列

尝试使用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

相关问题 更多 >

    热门问题