Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update chadwick register access #309

Merged
merged 2 commits into from
Feb 13, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions pybaseball/playerid_lookup.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
from difflib import get_close_matches
import io
import os
import re
import zipfile

from typing import List, Tuple
from typing import List, Tuple, Iterable

import pandas as pd
import requests

from . import cache

url = "https://raw.githubusercontent.com/chadwickbureau/register/master/data/people.csv"
url = "https://github.com/chadwickbureau/register/archive/refs/heads/master.zip"
PEOPLE_FILE_PATTERN = re.compile("/people.+csv$")

_client = None

Expand All @@ -18,6 +21,21 @@ def get_register_file():
return os.path.join(cache.config.cache_directory, 'chadwick-register.csv')


def _extract_people_files(zip_archive: zipfile.ZipFile) -> Iterable[zipfile.ZipInfo]:
return filter(
lambda zip_info: re.search(PEOPLE_FILE_PATTERN, zip_info.filename),
zip_archive.infolist(),
)


def _extract_people_table(zip_archive: zipfile.ZipFile) -> pd.DataFrame:
dfs = map(
lambda zip_info: pd.read_csv(io.BytesIO(zip_archive.read(zip_info.filename))),
_extract_people_files(zip_archive),
)
return pd.concat(dfs, axis=0)


@cache.df_cache()
def chadwick_register(save: bool = False) -> pd.DataFrame:
''' Get the Chadwick register Database '''
Expand All @@ -30,7 +48,9 @@ def chadwick_register(save: bool = False) -> pd.DataFrame:
s = requests.get(url).content
mlb_only_cols = ['key_retro', 'key_bbref', 'key_fangraphs', 'mlb_played_first', 'mlb_played_last']
cols_to_keep = ['name_last', 'name_first', 'key_mlbam'] + mlb_only_cols
table = pd.read_csv(io.StringIO(s.decode('utf-8')), usecols=cols_to_keep)
table = _extract_people_table(
zipfile.ZipFile(io.BytesIO(s))
).loc[:, cols_to_keep]

table.dropna(how='all', subset=mlb_only_cols, inplace=True) # Keep only the major league rows
table.reset_index(inplace=True, drop=True)
Expand Down