I wrote a code for json file and export it into excel with pandas module. I added if filter in for-loop and print function displaying true in terms of this filter. But in excel file, its not filtering output. How can I modify it? Thank you.
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 = [Game.from_json(game) for game in jsondata["Value"]]
for game in games:
if "Bundesliga" in game.league or "Arsenal" in game.hometeam:
continue
print(game)
df=pd.DataFrame(games)
df.to_excel("output.xlsx")
print("Saved.")
CodePudding user response:
Move the conditions into your list comprehension:
games = [Game.from_json(game) for game in jsondata["Value"] if "Bundesliga" not in game.league and "Arsenal" not in game.hometeam]
The subsequent loop doesn't change the original list.