-
Notifications
You must be signed in to change notification settings - Fork 1
/
table_parser.py
179 lines (137 loc) · 4.58 KB
/
table_parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import os
import json
import pathlib
import eland as ed
import pandas as pd
from elasticsearch import Elasticsearch
from slugify import slugify
from typer import Typer
app = Typer()
column_values = {
"INSTNM": str,
"INSTURL": str,
"CITY": str,
"ST_FIPS": int,
"PBI": float,
"ANNHI": float,
"TRIBAL": float,
"AANAPII": float,
"HSI": float,
"NANTI": float,
"HBCU": float,
"CURROPER": float,
"LATITUDE": float,
"LONGITUDE": float,
"MENONLY": float,
"WOMENONLY": float,
"CONTROL": int,
"RELAFFIL": str,
"HIGHDEG": str,
"MAIN": float,
"HCM2": float,
}
def _translate_code(json_file, df_column, if_None: str="Unknown"):
j_file = json.loads(pathlib.Path(json_file).read_text())
return lambda x:j_file.get(str(x), if_None)
converter_list = [
("RELAFFIL", _translate_code("translations/relaffil.json", "RELAFFIL", if_None="None")),
("CONTROL", _translate_code("translations/control.json", "CONTROL")),
("ST_FIPS", _translate_code("translations/st_fips.json", "ST_FIPS")),
("HIGHDEG", _translate_code("translations/high_deg.json", "HIGHDEG")),
]
converters = {x:y for x,y in converter_list} # To return "ST_FIPS": lambda x:st_fips_json.get(str(x), "Unknown"), etc
base_df = pd.read_csv(
"base_data/Most-Recent-Cohorts-All-Data-Elements.csv",
usecols=list(column_values.keys()),
converters=converters,
dtype=column_values,
)
base_df.fillna(0, inplace=True)
base_df['location'] = base_df.apply(lambda x:f"{x.LATITUDE}, {x.LONGITUDE}", axis=1)
# Create DATAFRAME FOR ACTIVE HBCUs and PBIs
hbcus = base_df.loc[(base_df.HBCU == 1) & (base_df.CURROPER == 1)]
pbis = base_df.loc[(base_df.PBI == 1) & (base_df.CURROPER == 1)]
def _gen_slug_link(school):
"""create markdown link to associated pages object"""
slug = slugify(school.INSTNM)
return f"[{school.INSTNM}](/pages/{slug}.md) - {school.INSTURL}"
@app.command()
def gen_list(
filename: pathlib.Path = "readme.md", title="HBCUs in the the United States"
):
"""build readme with readme_templates"""
states = []
for df in (hbcus, pbis):
df["readme"] = df.apply(_gen_slug_link, axis=1)
for name in sorted(df["ST_FIPS"].unique()):
state_sections = {}
for df_name, df in (("hbcus", hbcus), ("pbis", pbis)):
schools = df[df["ST_FIPS"] == name]["readme"].values.tolist()
if schools:
schools = "\n\n".join(schools)
else:
schools = "None"
state_sections[df_name] = schools
state_section = f"""## {name}
### HBCUs
{state_sections['hbcus']}
### PBIs
{state_sections['pbis']}"""
states.append(state_section)
states = "\n".join(states)
filename.write_text(
f"""# {title}
{states}
---
#### source:
[College Scorecard US Dept. of Education](https://data.ed.gov/dataset/college-scorecard-all-data-files-through-6-2020/resources?resource=823ac095-bdfc-41b0-b508-4e8fc3110082)
#### license: [MIT License](/LICENSE)"""
)
# Elastic Load Data
client = Elasticsearch(
cloud_id=os.environ.get("ES_CLOUD_ID"),
http_auth=(
os.environ.get("ES_USERNAME"),
os.environ.get("ES_PASSWORD"),
),
)
es_type_overrides = {
"location": "geo_point",
}
@app.command()
def load_to_es():
ed.pandas_to_eland(
pd_df=base_df,
es_client=client,
es_dest_index=f"US_COLLEGES".lower(),
es_if_exists="replace",
es_refresh=True,
use_pandas_index_for_es_ids=False,
es_type_overrides = es_type_overrides,
)
@app.command()
def build_pages(): # TODO REMOVE DEPENDENCY ON WIKIPEDIA
for df in (hbcus, pbis):
df.drop(columns=['CURROPER', 'LATITUDE', 'LONGITUDE'], inplace=True)
dfj = df.to_dict(orient="records")
for row in dfj:
f_meta = []
f_name = row.pop('INSTNM')
filepath = pathlib.Path(slugify(f_name)).with_suffix(".md")
f_url = row.pop('INSTURL').rstrip('/')
for name, val in row.items():
if val in (1.0, 0.0):
if val:
f_name += f" - {name}"
else:
f_meta.append(f"**{name}**: {val}")
f_text = "\n\n".join(f_meta)
page = pathlib.Path("pages").joinpath(filepath)
page.write_text(
f"""# {f_name}
### {f_url}
---
{f_text}"""
)
if __name__ == "__main__":
app()