From “Table reshaping and joins”#

Last updated: 2023-02-25 13:37:55

Exercise 06-b#

import numpy as np
import pandas as pd

# Read data
dat = pd.read_csv("data/ZonAnn.Ts+dSST.csv")
cols = ["90S-64S", "64S-44S", "44S-24S", "24S-EQU", "EQU-24N", "24N-44N", "44N-64N", "64N-90N"]
regions = dat[cols]

# Function to calculate linear slope
def f(x, y): 
    return np.polyfit(x, y, 1)[0]
f(dat["Year"], regions["44S-24S"])
0.006632501451200826
# Calculate slopes per region
regions.apply(lambda i: f(dat["Year"], i), axis=0)
90S-64S    0.006063
64S-44S    0.005141
44S-24S    0.006633
24S-EQU    0.006420
EQU-24N    0.006456
24N-44N    0.008097
44N-64N    0.011755
64N-90N    0.018612
dtype: float64

Exercise 06-d#

import pandas as pd

# Read
routes = pd.read_csv("data/gtfs/routes.txt")
trips = pd.read_csv("data/gtfs/trips.txt")

# Join
dat = pd.merge(trips, routes, on="route_id", how="left")

# Calculate number of unique trips per route
dat = dat.groupby(["route_id", "route_short_name", "route_long_name"]).nunique()["trip_id"].reset_index()

# Sort
dat = dat.sort_values("trip_id", ascending=False)

# Print
dat
route_id route_short_name route_long_name trip_id
678 2256 4 מסוף הטייסים-תל אביב יפו<->מסוף... 1001
677 2255 4 מסוף רידינג/רציפים-תל אביב יפו<... 934
3170 11525 6 אבי עזרי א-מודיעין עילית<->רמב'... 840
3171 11526 6 שדרות בית שמאי/שדרות בית הלל-מו... 830
2746 10509 1 קדושת לוי/שלום רב-ביתר עילית<->... 748
... ... ... ... ...
2291 9539 24 חמת גדר-עמק הירדן<->ת. מרכזית ט... 1
1190 4402 251 ת. מרכזית המפרץ/רציפים בינעירונ... 1
1199 4443 271 ת. מרכזית נהריה/רציפים-נהריה<->... 1
1204 4450 273 אוניברסיטה/רב תכליתי-חיפה<->ת. ... 1
7250 29368 21 נהריה-נהריה<->תל אביב ההגנה-תל ... 1

7251 rows × 4 columns

Exercise 06-e#

import pandas as pd
trips = pd.read_csv("data/gtfs/trips.txt")
trips[["route_id", "shape_id"]].groupby("route_id").nunique().reset_index()["shape_id"].value_counts()
1    7135
2     112
0       4
Name: shape_id, dtype: int64

Exercise 06-f#

import pandas as pd

# Read
stops = pd.read_csv("data/gtfs/stops.txt")
stop_times = pd.read_csv("data/gtfs/stop_times.txt")

# Subset columns
stops = stops[["stop_id", "stop_name", "stop_lon", "stop_lat"]]
stop_times = stop_times[["trip_id", "arrival_time", "stop_id", "stop_sequence", "shape_dist_traveled"]]

# Subset specific trip
sel = stop_times["trip_id"] == "55745843_180421"
stop_times = stop_times[sel]

# How many stops in the trip?
stop_times.shape[0]
32
# Join stops to stop times
stop_times = pd.merge(stop_times, stops)

# At what time there is a stop at "מרכז הספורט אוניברסיטת בן גוריון"
sel = stop_times["stop_name"] == "מרכז הספורט אוניברסיטת בן גוריון"
stop_times[sel]["arrival_time"].iloc[0]
'08:37:21'
# Total distance traveled in trip
sel = stop_times["stop_sequence"] == max(stop_times["stop_sequence"])
stop_times[sel]["shape_dist_traveled"].iloc[0]
12767
# Pair of stations closest to each other
id = stop_times["shape_dist_traveled"].diff().idxmin()
stop_times["stop_name"].iloc[[id-1, id]]
21    מרכז רפואי סורוקה/אוניברסיטת בן...
22            מרכז רפואי סורוקה/יצחק רגר
Name: stop_name, dtype: object
# Pair of stations farthest from each other
id = stop_times["shape_dist_traveled"].diff().idxmax()
stop_times["stop_name"].iloc[[id-1, id]]
0                  מסוף רמות
1    בי''ס יפה נוף/נחום שריג
Name: stop_name, dtype: object

Exercise 06-g#

import pandas as pd

# Get total distance traveled per 'trip_id'
stop_times = pd.read_csv("data/gtfs/stop_times.txt")
stop_times = stop_times[["trip_id", "shape_dist_traveled"]].groupby("trip_id").max()
stop_times = stop_times.reset_index()
# Join with trips to get 'route_id' per trip
trips = pd.read_csv("data/gtfs/trips.txt")
trips = trips[["trip_id", "route_id"]]
trips = pd.merge(trips, stop_times, on="trip_id")
trips = trips.groupby("route_id").first()
trips = trips.reset_index()
# Join with routes to get route short/long names
routes = pd.read_csv("data/gtfs/routes.txt")
routes = routes[["route_id", "route_short_name", "route_long_name"]]
routes = pd.merge(routes, trips, on="route_id")
# Sort accordinge to distance traveled
routes = routes.sort_values("shape_dist_traveled", ascending=False).head()
routes.head()["route_long_name"].to_list()
['ת. מרכזית חוף הכרמל/רציפים בינעירוני-חיפה<->ת. מרכזית אילת/הורדה-אילת-2#',
 'ת. מרכזית אילת/רציפים-אילת<->ת. מרכזית חוף הכרמל/הורדה-חיפה-1#',
 'ת. מרכזית אילת/רציפים-אילת<->ת. מרכזית חוף הכרמל/הורדה-חיפה-1#',
 'ת. מרכזית חוף הכרמל/רציפים בינעירוני-חיפה<->ת. מרכזית אילת/הורדה-אילת-2#',
 'ת. מרכזית המפרץ/רציפים בינעירוני-חיפה<->ת. מרכזית אילת/הורדה-אילת-2#']