import pandas as pd from datetime import datetime import os import sys import re import…
- User
import pandas as pd from datetime import datetime import os import sys import re import matplotlib.pyplot as plt import matplotlib.colors as mcolors import math from collections import deque import numpy as np
-------------------------
Step 1: Load the Data from Excel
-------------------------
def load_data(file_path, skip_rows=0): """ Attempts to load the Excel file, skipping a specified number of rows. Iteratively skips more rows until the required columns are found.
Parameters: file_path (str): The path to the Excel file. skip_rows (int): Number of rows to skip at the top of the file. Returns: df (DataFrame): The loaded DataFrame. header_row (int): The row number used as headers. """ max_skip = 10 # Maximum rows to skip to find headers for skip in range(skip_rows, skip_rows + max_skip): try: df = pd.read_excel(file_path, header=skip) # Clean column names df = clean_column_names(df) # Define required columns with cleaned names required_columns = [ 'Date', 'Kick_Off_(local)', 'Home_Team', 'Away_Team', 'Home_Score', 'Away_Score', 'Home_Odds', 'Away_Odds' ] # Verify required columns are present verify_columns(df, required_columns) print(f"Successfully loaded data with header row at line {skip + 1}.\n") return df, skip except FileNotFoundError: print(f"Error: The file at path '{file_path}' does not exist.") sys.exit(1) except KeyError as e: print(e) print(f"Attempting to skip {skip + 1} rows and try again...\n") except Exception as e: print(f"An unexpected error occurred: {e}") print(f"Attempting to skip {skip + 1} rows and try again...\n") raise Exception("Unable to locate the required header row in the Excel file.")-------------------------
Step 2: Clean Column Names
-------------------------
def clean_column_names(df): """ Cleans the column names by stripping leading/trailing spaces, replacing spaces with underscores, removing non-printable characters, and standardizing casing.
Parameters: df (DataFrame): The DataFrame whose columns need to be cleaned. Returns: df (DataFrame): The DataFrame with cleaned column names. """ # Remove non-printable characters df.columns = df.columns.str.replace(r'[^\x00-\x7F]+', '', regex=True) # Strip leading/trailing spaces df.columns = df.columns.str.strip() # Replace spaces with underscores df.columns = df.columns.str.replace(' ', '_') print("Column names after cleaning:") print(df.columns.tolist(), "\n") return df-------------------------
Step 3: Verify Required Columns
-------------------------
def verify_columns(df, required_columns): """ Verifies that all required columns are present in the DataFrame.
- Assistant