<jupyter_start><jupyter_text>1- Imports<jupyter_code>from selenium import webdriver
from selenium.webdriver.support.ui import Select

from os import getcwd, remove
# from pdb import set_trace as st
from ipdb import set_trace as st

from time import sleep

from glob import glob

from zipfile import ZipFile

import pandas as pd

from IPython.display import display
pd.options.display.max_columns = None<jupyter_output><empty_output><jupyter_text>2- Retreiving data<jupyter_code>def initate_browser():
    # config for now showing the download popup and setting the download dir
    
    # url = "https://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=258"
    
#     data for US carriers, demosetic and international
    url = "https://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=308"
#     profile = webdriver.FirefoxProfile()
    profile.set_preference('browser.download.folderList', 2) # custom location
    profile.set_preference("browser.download.manager.showWhenStarting", False)
    profile.set_preference("browser.download.manager.showAlertOnComplete", False)
    profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/zip, text/html, application/x-zip-compressed')
    profile.set_preference("browser.helperApps.neverAsk.openFile",'application/zip, text/html, application/x-zip-compressed')
    profile.set_preference('browser.download.dir', getcwd())

    browser = webdriver.Firefox(profile)
    browser.get(url)
    
    #set AllVars's tickbox
    browser.find_element_by_css_selector('#AllVars').click()

    return browser
def download_file_year(browser, year):
    select = Select(browser.find_element_by_css_selector('#XYEAR'))
    select.select_by_value(str(year))
    browser.find_element_by_css_selector('.tsbutton').click()
def check_if_file_are_downloaded():
    return len(glob("*.zip")) == len(range(1990, 2020))
def check_if_final_csv_is_made():
    return  bool(glob("data.csv"))
def download_files():
    browser = initate_browser()
    for year in range(1990, 2020):
        download_file_year(browser, year)
        sleep(10)
# download_file_year(browser, 2001)

def concatinate_files():
    list_of_dfs = []
    for file_name in glob("*.zip"):
        zipObj = ZipFile(file_name, "r")
        zipObj.extractall()
        csv_file_name = glob("*.csv")[0]
        temp_df = pd.read_csv(csv_file_name)
        list_of_dfs.append(temp_df)
        remove(csv_file_name)
#         print("z")

    full_df = pd.concat(list_of_dfs, axis=0)
    full_df.to_csv("data.csv")
def remove_extra_zip_files():
    for file in glob("*.zip"):
        remove(file)
def get_data():
    # check if final concatinated data.csv is already made
    if not check_if_final_csv_is_made():
        # check if zip files are downloaded
        if not check_if_file_are_downloaded():
            initate_browser()
            download_files()
        concatinate_files()
        remove_extra_zip_files()
get_data()<jupyter_output><empty_output><jupyter_text>3- Cleaning data  3-1 selecting columns, correcting dtypes, removing nulls<jupyter_code>if "df" not in locals():
    df = pd.read_csv("./data.csv")
needed_columns = [
    "UNIQUE_CARRIER_NAME",
    "CARRIER_NAME",
    "YEAR",
    "MONTH",
    "QUARTER",
    "PASSENGERS",
    "FREIGHT",
    "MAIL",
    "DISTANCE",
]
if "sub_df" not in locals():
    sub_df = df.copy()
    del df
    sub_df = sub_df[needed_columns]
sub_df
# correcting the dtypes

sub_df = sub_df.astype(
    {
        "PASSENGERS": "int", 
        "FREIGHT": "int", 
        "MAIL": "int", 
        "DISTANCE": "int"
    }
)
# checking for null values

sub_df.isna().sum()
sub_df = sub_df.dropna(axis=0)

# be sure that there are no nans
assert sub_df.isna().sum().sum() == 0<jupyter_output><empty_output><jupyter_text>3-2 removing outliers<jupyter_code>grouped_carrier = sub_df.groupby("UNIQUE_CARRIER_NAME").count()["YEAR"]

# keeping only carriers with more than 10000 total flights
list_of_valid_carriers = grouped_carrier[grouped_carrier > 10000].index.to_numpy()
sub_df = sub_df[sub_df["UNIQUE_CARRIER_NAME"].isin(list_of_valid_carriers)]

sub_df["PASSENGERS_x_DISTANCE"] = sub_df["PASSENGERS"] * sub_df["DISTANCE"]
sub_df["FREIGHT_x_DISTANCE"] = sub_df["FREIGHT"] * sub_df["DISTANCE"]
sub_df["MAIL_x_DISTANCE"] = sub_df["MAIL"] * sub_df["DISTANCE"]

sub_df
# TEST
tt = sub_df.groupby("UNIQUE_CARRIER_NAME").sum()
tt.sort_values(by="PASSENGERS_x_DISTANCE")
# tt_df["date"] = 
"{}-{}-01".format(sub_df["YEAR"].astype("str"), sub_df["MONTH"].astype("str"))
grouped_carrier_year_month = sub_df.groupby(["UNIQUE_CARRIER_NAME", "YEAR", "MONTH"]).count()

grouped_carrier_year_month
tt = sub_df.groupby(["UNIQUE_CARRIER_NAME", "YEAR", "MONTH"]).count()
tt<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12969211303247574, 'fraction_numerical': 0.010965837199493884, 'mean_word_length': 4.573443008225617, 'pattern_counts': {'":': 4, '<': 17, '<?xml version=': 0, '>': 18, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '530121', 'license': 'MIT', 'n_tokens_mistral': 1756, 'n_tokens_neox': 1671, 'n_words': 300, 'path': 'module3-permutation-boosting/HADI_MODARES_LS_DS_233_assignment.ipynb', 'repo_name': 'hadi-M/DS-Unit-2-Applied-Modeling', 'size': '4742'}