为了账号安全,请及时绑定邮箱和手机立即绑定

将嵌套的 JSON 转换为 Dataframe

将嵌套的 JSON 转换为 Dataframe

手掌心 2021-11-09 14:31:26
我有一个如下所示的嵌套 JSON。我想将其转换为熊猫数据框。作为其中的一部分,我还只需要解析权重值。我不需要单位。我还希望将数字值从字符串转换为数字。任何帮助,将不胜感激。我对python比较陌生。谢谢你。JSON 示例:{'id': '123', 'name': 'joe', 'weight': {'number': '100', 'unit': 'lbs'}, 'gender': 'male'}示例输出如下:id     name    weight    gender123    joe     100       male
查看完整描述

3 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

使用“ from pandas.io.json import json_normalize ”。


id     name    weight.number  weight.unit  gender

123    joe     100              lbs        male


查看完整回答
反对 回复 2021-11-09
?
慕哥6287543

TA贡献1831条经验 获得超10个赞

如果您想丢弃重量单位,只需将 json 展平:


temp = {'id': '123', 'name': 'joe', 'weight': {'number': '100', 'unit': 'lbs'}, 'gender': 'male'}

temp['weight'] = temp['weight']['number']

然后把它变成一个数据框:


pd.DataFrame(temp)


查看完整回答
反对 回复 2021-11-09
?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

像这样的事情应该可以解决问题:


json_data = [{'id': '123', 'name': 'joe', 'weight': {'number': '100', 'unit': 'lbs'}, 'gender': 'male'}]

# convert the data to a DataFrame

df = pd.DataFrame.from_records(json_data)

# conver id to an int

df['id'] = df['id'].apply(int)

# get the 'number' field of weight and convert it to an int

df['weight'] = df['weight'].apply(lambda x: int(x['number']))

df


查看完整回答
反对 回复 2021-11-09
  • 3 回答
  • 0 关注
  • 187 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信