pandas读取json文件并进行刷选导出xlsx文件

该博客介绍了如何使用Pandas库读取JSON文件,并从中筛选特定数据。首先,读取JSON文件并提取所需数组,然后通过`json_normalize`函数规范化数据。接着,分别筛选出包含特定节目的数据(如The X-Files Lost Buffy the Vampire Slayer),并将这些筛选结果保存到不同的Excel工作表中。整个过程展示了Pandas在数据处理和导出上的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pandas读取json文件并进行刷选导出xlsx文件

原始json数据
在这里插入图片描述

import pandas as pd
import pprint

# 读取json文件
df_tv_shows = pd.read_json("datas/tv_shows.json")
# 读取json文件中shows数组下所有数据
first_obj = df_tv_shows.loc[:, "shows"]
# 将shows数组数据读出,其中episodes是shows下的数组
df_tmp = pd.json_normalize(data=first_obj, record_path="episodes", meta=["show", "runtime","network"])
pprint.pprint(df_tmp)

# 刷选出show=The X-Files
df_tmp1=df_tmp[df_tmp["show"]=="The X-Files"]
print(df_tmp1.head())
print(df_tmp1.info())

# 刷选出show=Lost
df_tmp2=df_tmp[df_tmp["show"]=="Lost"]
print(df_tmp2.head())
print(df_tmp2.info())

# 刷选出show=Buffy the Vampire Slayer
df_tmp3=df_tmp[df_tmp["show"]=="Buffy the Vampire Slayer"]
print(df_tmp3.head())
print(df_tmp3.info())


# 将刷选出三组数据导出为xlsx文件
#xlsx文件名称
excel_file = pd.ExcelWriter("episodes.xlsx")
df_tmp1.to_excel(excel_writer=excel_file,
             sheet_name = "xfiles",
             index = False)
df_tmp2.to_excel(excel_writer=excel_file,
             sheet_name = "lost",
             index = False)
df_tmp3.to_excel(excel_writer=excel_file,
             sheet_name = "vampire",
             index = False)
excel_file.save()

df_tmp数据格式如下:
在这里插入图片描述
最后导出的xlxs文件:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值