forked from tylerjrichards/Streamlit-for-Data-Science
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjob_streamlit.py
240 lines (206 loc) · 8.1 KB
/
job_streamlit.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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import pandas as pd
import requests
import streamlit as st
from streamlit_lottie import st_lottie
password_attempt = st.text_input("Please Enter The Password")
if password_attempt != "example_password":
st.write("Incorrect Password!")
st.stop()
def load_lottieurl(url: str):
r = requests.get(url)
if r.status_code != 200:
return None
return r.json()
lottie_airplane = load_lottieurl(
"https://assets4.lottiefiles.com/packages/lf20_jhu1lqdz.json"
)
st_lottie(lottie_airplane, speed=1, height=200, key="initial")
st.title("Major US Airline Job Application")
st.write("by Tyler Richards")
st.subheader("Question 1: Airport Distance")
"""
The first exercise asks us 'Given the table of airports and
locations (in latitude and longitude) below,
write a function that takes an airport code as input and
returns the airports listed from nearest to furthest from
the input airport.' There are three steps here:
1. Load Data
2. Implement Distance Algorithm
3. Apply distance formula across all airports other than the input
4. Return sorted list of airports Distance
"""
airport_distance_df = pd.read_csv("airport_location.csv")
st.write(airport_distance_df)
with st.echo():
# load necessary data
airport_distance_df = pd.read_csv("airport_location.csv")
"""
From some quick googling, I found that the haversine distance is
a good approximation for distance. At least good enough to get the
distance between airports! Haversine distances can be off by up to .5%,
because the earth is not actually a sphere. It looks like the latitudes
and longitudes are in degrees, so I'll make sure to have a way to account
for that as well. The haversine distance formula is labeled below,
followed by an implementation in python
"""
st.image("haversine.png")
with st.echo():
from math import atan2, cos, radians, sin, sqrt
def haversine_distance(long1, lat1, long2, lat2, degrees=False):
# degrees vs radians
if degrees == True:
long1 = radians(long1)
lat1 = radians(lat1)
long2 = radians(long2)
lat2 = radians(lat2)
# implementing haversine
a = (
sin((lat2 - lat1) / 2) ** 2
+ cos(lat1) * cos(lat2) * sin((long2 - long1) / 2) ** 2
)
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = 6371 * c # radius of earth in kilometers
return distance
# execute haversine function definition
from math import atan2, cos, radians, sin, sqrt
def haversine_distance(long1, lat1,
long2, lat2,
degrees=False):
# degrees vs radians
if degrees == True:
long1 = radians(long1)
lat1 = radians(lat1)
long2 = radians(long2)
lat2 = radians(lat2)
# implementing haversine
a = (
sin((lat2 - lat1) / 2) ** 2
+ cos(lat1) * cos(lat2) * sin((long2 - long1) / 2) ** 2
)
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = 6371 * c # radius of earth in kilometers
return distance
"""
Now, we need to test out our function! The
distance between the default points is
18,986 kilometers, but feel free to try out
your own points of interest.
"""
long1 = st.number_input("Longitude 1", value=2.55)
long2 = st.number_input("Longitude 2", value=172.00)
lat1 = st.number_input("Latitude 1", value=49.01)
lat2 = st.number_input("Latitude 2", value=-43.48)
test_distance = haversine_distance(
long1=long1, long2=long2, lat1=lat1, lat2=lat2, degrees=True
)
st.write("Your distance is: {} kilometers".format(int(test_distance)))
"""
We have the Haversine distance implemented, and we also have
proven to ourselves that it works reasonably well.
Our next step is to implement this in a function!
"""
def get_distance_list(airport_dataframe,
airport_code):
df = airport_dataframe.copy()
row = df[df.loc[:, "Airport Code"] == airport_code]
lat = row["Lat"]
long = row["Long"]
df = df[df["Airport Code"] != airport_code]
df["Distance"] = df.apply(
lambda x: haversine_distance(
lat1=lat, long1=long, lat2=x.Lat, long2=x.Long, degrees=True
),
axis=1,
)
df_to_return = df.sort_values(by="Distance").reset_index()
return df_to_return
with st.echo():
def get_distance_list(airport_dataframe, airport_code):
df = (
airport_dataframe.copy()
) # creates a copy of our dataframe for our function to use
row = df[
df.loc[:, "Airport Code"] == airport_code
] # selects the row from our airport code input
lat = row["Lat"] # get latitude
long = row["Long"] # get longitude
df = df[
df["Airport Code"] != airport_code
] # filter out our airport, implement haversine distance
df["Distance"] = df.apply(
lambda x: haversine_distance(
lat1=lat, long1=long, lat2=x.Lat, long2=x.Long, degrees=True
),
axis=1,
)
df_to_return = df.sort_values(by="Distance").reset_index()
return df_to_return # return values sorted
"""
To use this function, select an airport from the airports provided in the dataframe
and this application will find the distance between each one, and
return a list of the airports closest to furthest.
"""
selected_airport = st.selectbox("Airport Code", airport_distance_df["Airport Code"])
distance_airports = get_distance_list(
airport_dataframe=airport_distance_df, airport_code=selected_airport
)
st.write("Your closest airports in order are {}".format(list(distance_airports)))
"""
This all seems to work just fine! There are a few ways I would improve this if I was working on
this for a longer period of time.
1. I would implement the [Vincenty Distance](https://en.wikipedia.org/wiki/Vincenty%27s_formulae)
instead of the Haversine distance, which is much more accurate but cumbersome to implement.
2. I would vectorize this function and make it more efficient overall.
Because this dataset is only 7 rows long, it wasn't particularly important,
but if this was a crucial function that was run in production we would want to vectorize it for speed.
"""
st.subheader("Question 2: Representation")
"""
For this transformation, there are a few things
that I would start with. First, I would have to define
what a unique trip actually was. In order to do this, I would
group by the origin, the destination, and the departure date
(for the departure date, often customers will change around
this departure date, so we should group by the date plus or
minus at least 1 buffer day to capture all the correct dates).
Additionally, we can see that often users search from an entire city,
and then shrink that down into a specific airport. So we should also
consider a group of individual queries from cities and airports in the
same city, as the same search, and do the same for destination.
From that point, we should add these important columns to each unique search.
"""
example_df = pd.DataFrame(
columns=[
"userid",
"number_of_queries",
"round_trip",
"distance",
"number_unique_destinations",
"number_unique_origins",
"datetime_first_searched",
"average_length_of_stay",
"length_of_search",
]
)
example_row = {
"userid": 98593,
"number_of_queries": 5,
"round_trip": 1,
"distance": 893,
"number_unique_destinations": 5,
"number_unique_origins": 1,
"datetime_first_searched": "2015-01-09",
"average_length_of_stay": 5,
"length_of_search": 4,
}
st.write(example_df.append(example_row, ignore_index=True))
"""
For answering the second part of the question, we should take the euclidian distance
on two normalized vectors. There are two solid options for comparing two
entirely numeric rows, the euclidian distance (which is just the straight line
difference between two values), and the manhattan distance (think of this as the
distance traveled if you had to use city blocks to travel diagonally across manhattan).
Because we have normalized data, and the data is not high dimensional or sparse, I
would recommend using the euclidian distance to start off. This distance would tell
us how similar two trips were.
"""