将包含JSON对象的数据框扩展为更大的数据框 [英] Expand Dataframe containing JSON object into larger dataframe

查看:89
本文介绍了将包含JSON对象的数据框扩展为更大的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在熊猫中有一个带有两列的数据框.一个是ID,另一个是一个长JSON对象,对于数据帧中的每个对象而言,这都是相同的对象.我的目标是为JSON对象中的每个键创建列.

I have a dataframe in pandas with two columns. One is an ID and the other is a long JSON object, which is the same object for each object in the dataframe. My goal here is to create columns for each key in the JSON object.

这是输入示例

ID  request_json
175431467   {"Rate":"50","Groups":"7 months - 3 years"

我想将此扩展为一个包含三列的数据框:ID,Rate和Groups.

I'd like to expand this into a dataframe with three columns: ID, Rate, and Groups.

做到这一点的最佳方法是什么?

What's the best way to do this?

推荐答案

您可以将DataFrame构造函数与joinconcat一起使用:

You can use DataFrame constructor with join or concat:

import json

df = df[['ID']].join(pd.DataFrame(df['request_json'].apply(json.loads).values.tolist()))
print (df)
          ID              Groups Rate
0  175431467  7 months - 3 years   50

或者:

df = pd.concat([df['ID'],
                pd.DataFrame(df['request_json'].apply(json.loads).values.tolist())], axis=1)
print (df)
          ID              Groups Rate
0  175431467  7 months - 3 years   50

这篇关于将包含JSON对象的数据框扩展为更大的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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