扁平化嵌套的JSON,并使用熊猫连接到数据框

时间:2020-08-04 18:00:46

标签: python json pandas normalize

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

我的熊猫数据框如下:

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)

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

2 个答案:

答案 0 :(得分:2)

尝试使用literal_eval标准库中的ast

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

答案 1 :(得分:0)

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

chuck = []

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

test_df = pd.concat(chuck)

然后删除test_df的重复列