使用Pandas将JSON转Excel时过滤逻辑未生效的修正咨询
问题解决:导出Excel未应用过滤条件的修改方案
你的问题核心是:循环里的过滤只做了打印,没有修改用于生成DataFrame的原始列表,所以导出Excel时还是用了全部数据。以下是两种修改方式:
方式一:提前过滤(推荐,更高效)
在生成games列表时直接加入过滤条件,避免先创建全量数据再过滤:
import json import contextlib import pandas as pd class Game: @classmethod def from_json(cls, json_record): game = cls() game.league = json_record["ligler"] game.hometeam = None game.awayteam = None game.score = None if game_a := json_record: with contextlib.suppress(IndexError): game.hometeam = game_a.get("team1") with contextlib.suppress(IndexError): game.awayteam = game_a.get("team2") return game def __str__(self): return ','.join( str(item) for item in ( self.league, self.hometeam, self.awayteam, self.score)) with open("example.json") as f: jsondata = json.load(f) # 生成列表时直接过滤 games = [] for game_data in jsondata["Value"]: game = Game.from_json(game_data) if not ("Bundesliga" in game.league or "Arsenal" in game.hometeam): games.append(game) print(game) df=pd.DataFrame(games) df.to_excel("output.xlsx") print("Saved.")
方式二:先生成全量数据再过滤
如果你需要保留全量games列表做其他操作,可以单独生成过滤后的列表:
# 原代码中生成games的部分不变 games = [Game.from_json(game) for game in jsondata["Value"]] # 生成过滤后的列表 filtered_games = [] for game in games: if not ("Bundesliga" in game.league or "Arsenal" in game.hometeam): filtered_games.append(game) print(game) # 用过滤后的列表生成DataFrame df=pd.DataFrame(filtered_games) df.to_excel("output.xlsx") print("Saved.")
关键说明
两种方式的核心都是让DataFrame基于过滤后的列表创建,而不是原始的全量games列表。你之前的代码只是在循环里跳过不符合条件的项打印,但没有改变games的内容,所以导出时还是用了全部数据。
内容的提问来源于stack exchange,提问作者intpanda
相关产品推荐
相关产品推荐

