如何将json列迭代到列,然后附加原始数据帧? [英] How to iterate json column to columns and then append origin dataframe?

查看:73
本文介绍了如何将json列迭代到列,然后附加原始数据帧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import pandas as pd
inp = [{'c1':10,'cols':{'c2':20,'c3':'str1'}, 'c4':'41'}, {'c1':11,'cols':{'c2':20,'c3':'str2'},'c4':'42'}, {'c1':12,'cols':{'c2':20,'c3':'str3'},'c4':'43'}]
df = pd.DataFrame(inp)
print (df)

df是:

   c1  c4                      cols
0  10  41  {'c2': 20, 'c3': 'str1'}
1  11  42  {'c2': 20, 'c3': 'str2'}
2  12  43  {'c2': 20, 'c3': 'str3'}

cols列是JSON类型.

The cols column is JSON type.

我需要将cols列设置为json_decode,这意味着将df更改为:

I need to make cols column to json_decode,which means change df to:

   c1    c4    c2      c3
0  10    41    20      str1
1  11    42    20      str2
2  12    43    20      str3

该怎么做?
预先感谢!

How to do it?
Thanks in advance!

推荐答案

使用输出

    c1  c4  cols.c2 cols.c3
0   10  41  20      str1
1   11  42  20      str2
2   12  43  20      str3


如果您有pd.DataFrame,请使用to_dict


If you have a pd.DataFrame, convert back using to_dict

pd.io.json.json_normalize(df.to_dict('records'))

这篇关于如何将json列迭代到列,然后附加原始数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆