├── data └── green │ └── for_gh.txt ├── images └── img.png ├── docker-requirements.txt ├── requirements.txt ├── Dockerfile ├── blocks ├── make_gh_block.py ├── make_docker_block.py └── make_gcp_blocks.py ├── flows ├── 03_deployments │ ├── docker_deploy.py │ ├── parameterized_flow.py │ └── README.md ├── 02_gcp │ ├── etl_gcs_to_bq.py │ └── etl_web_to_gcs.py ├── 04_homework │ ├── el_gcs_to_bq.py │ ├── parameterized_flow_hw.py │ └── homework.md └── 01_start │ ├── ingest_data.py │ ├── ingest_data_flow.py │ └── README.md ├── .prefectignore ├── README.md ├── .gitignore ├── LICENSE └── exploration └── clean_taxi.ipynb /data/green/for_gh.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/img.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/discdiver/prefect-zoomcamp/HEAD/images/img.png -------------------------------------------------------------------------------- /docker-requirements.txt: -------------------------------------------------------------------------------- 1 | pandas==1.5.2 2 | prefect-gcp[cloud_storage]==0.2.4 3 | protobuf==4.21.11 4 | pyarrow==10.0.1 5 | pandas-gbq==0.18.1 -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pandas==1.5.2 2 | prefect==2.7.7 3 | prefect-sqlalchemy==0.2.2 4 | prefect-gcp[cloud_storage]==0.2.4 5 | protobuf==4.21.11 6 | pyarrow==10.0.1 7 | pandas-gbq==0.18.1 8 | psycopg2-binary==2.9.5 9 | sqlalchemy==1.4.46 -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM prefecthq/prefect:2.7.7-python3.9 2 | 3 | COPY docker-requirements.txt . 4 | 5 | RUN pip install -r docker-requirements.txt --trusted-host pypi.python.org --no-cache-dir 6 | 7 | COPY flows /opt/prefect/flows 8 | RUN mkdir -p /opt/prefect/data/yellow -------------------------------------------------------------------------------- /blocks/make_gh_block.py: -------------------------------------------------------------------------------- 1 | from prefect.filesystems import GitHub 2 | 3 | # alternative to creating GitHub block in the UI 4 | 5 | gh_block = GitHub( 6 | name="de-zoom", repository="https://github.com/discdiver/prefect-zoomcamp" 7 | ) 8 | 9 | gh_block.save("de-zoom", overwrite=True) 10 | -------------------------------------------------------------------------------- /blocks/make_docker_block.py: -------------------------------------------------------------------------------- 1 | from prefect.infrastructure.docker import DockerContainer 2 | 3 | # alternative to creating DockerContainer block in the UI 4 | docker_block = DockerContainer( 5 | image="discdiver/prefect:zoom", # insert your image here 6 | image_pull_policy="ALWAYS", 7 | auto_remove=True, 8 | ) 9 | 10 | docker_block.save("zoom", overwrite=True) 11 | -------------------------------------------------------------------------------- /flows/03_deployments/docker_deploy.py: -------------------------------------------------------------------------------- 1 | from prefect.deployments import Deployment 2 | from parameterized_flow import etl_parent_flow 3 | from prefect.infrastructure.docker import DockerContainer 4 | 5 | docker_block = DockerContainer.load("zoom") 6 | 7 | docker_dep = Deployment.build_from_flow( 8 | flow=etl_parent_flow, 9 | name="docker-flow", 10 | infrastructure=docker_block, 11 | ) 12 | 13 | 14 | if __name__ == "__main__": 15 | docker_dep.apply() 16 | -------------------------------------------------------------------------------- /.prefectignore: -------------------------------------------------------------------------------- 1 | # prefect artifacts 2 | .prefectignore 3 | 4 | # python artifacts 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | *.egg-info/ 9 | *.egg 10 | 11 | # Type checking artifacts 12 | .mypy_cache/ 13 | .dmypy.json 14 | dmypy.json 15 | .pyre/ 16 | 17 | # IPython 18 | profile_default/ 19 | ipython_config.py 20 | *.ipynb_checkpoints/* 21 | 22 | # Environments 23 | .python-version 24 | .env 25 | .venv 26 | env/ 27 | venv/ 28 | 29 | # MacOS 30 | .DS_Store 31 | 32 | # Dask 33 | dask-worker-space/ 34 | 35 | # Editors 36 | .idea/ 37 | .vscode/ 38 | 39 | # VCS 40 | .git/ 41 | .hg/ 42 | -------------------------------------------------------------------------------- /blocks/make_gcp_blocks.py: -------------------------------------------------------------------------------- 1 | from prefect_gcp import GcpCredentials 2 | from prefect_gcp.cloud_storage import GcsBucket 3 | 4 | # alternative to creating GCP blocks in the UI 5 | # copy your own service_account_info dictionary from the json file you downloaded from google 6 | # IMPORTANT - do not store credentials in a publicly available repository! 7 | 8 | 9 | credentials_block = GcpCredentials( 10 | service_account_info={} # enter your credentials from the json file 11 | ) 12 | credentials_block.save("zoom-gcp-creds", overwrite=True) 13 | 14 | 15 | bucket_block = GcsBucket( 16 | gcp_credentials=GcpCredentials.load("zoom-gcp-creds"), 17 | bucket="prefect-de-zoomcamp", # insert your GCS bucket name 18 | ) 19 | 20 | bucket_block.save("zoom-gcs", overwrite=True) 21 | -------------------------------------------------------------------------------- /flows/02_gcp/etl_gcs_to_bq.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | import pandas as pd 3 | from prefect import flow, task 4 | from prefect_gcp.cloud_storage import GcsBucket 5 | from prefect_gcp import GcpCredentials 6 | 7 | 8 | @task(retries=3) 9 | def extract_from_gcs(color: str, year: int, month: int) -> Path: 10 | """Download trip data from GCS""" 11 | gcs_path = f"data/{color}/{color}_tripdata_{year}-{month:02}.parquet" 12 | gcs_block = GcsBucket.load("zoom-gcs") 13 | gcs_block.get_directory(from_path=gcs_path, local_path=f"../data/") 14 | return Path(f"../data/{gcs_path}") 15 | 16 | 17 | @task() 18 | def transform(path: Path) -> pd.DataFrame: 19 | """Data cleaning example""" 20 | df = pd.read_parquet(path) 21 | print(f"pre: missing passenger count: {df['passenger_count'].isna().sum()}") 22 | df["passenger_count"].fillna(0, inplace=True) 23 | print(f"post: missing passenger count: {df['passenger_count'].isna().sum()}") 24 | return df 25 | 26 | 27 | @task() 28 | def write_bq(df: pd.DataFrame) -> None: 29 | """Write DataFrame to BiqQuery""" 30 | 31 | gcp_credentials_block = GcpCredentials.load("zoom-gcp-creds") 32 | 33 | df.to_gbq( 34 | destination_table="dezoomcamp.rides", 35 | project_id="prefect-sbx-community-eng", 36 | credentials=gcp_credentials_block.get_credentials_from_service_account(), 37 | chunksize=500_000, 38 | if_exists="append", 39 | ) 40 | 41 | 42 | @flow() 43 | def etl_gcs_to_bq(): 44 | """Main ETL flow to load data into Big Query""" 45 | color = "yellow" 46 | year = 2021 47 | month = 1 48 | 49 | path = extract_from_gcs(color, year, month) 50 | df = transform(path) 51 | write_bq(df) 52 | 53 | 54 | if __name__ == "__main__": 55 | etl_gcs_to_bq() 56 | -------------------------------------------------------------------------------- /flows/02_gcp/etl_web_to_gcs.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | import pandas as pd 3 | from prefect import flow, task 4 | from prefect_gcp.cloud_storage import GcsBucket 5 | from random import randint 6 | 7 | 8 | @task(retries=3) 9 | def fetch(dataset_url: str) -> pd.DataFrame: 10 | """Read taxi data from web into pandas DataFrame""" 11 | # if randint(0, 1) > 0: 12 | # raise Exception 13 | 14 | df = pd.read_csv(dataset_url) 15 | return df 16 | 17 | 18 | @task(log_prints=True) 19 | def clean(df: pd.DataFrame) -> pd.DataFrame: 20 | """Fix dtype issues""" 21 | df["tpep_pickup_datetime"] = pd.to_datetime(df["tpep_pickup_datetime"]) 22 | df["tpep_dropoff_datetime"] = pd.to_datetime(df["tpep_dropoff_datetime"]) 23 | print(df.head(2)) 24 | print(f"columns: {df.dtypes}") 25 | print(f"rows: {len(df)}") 26 | return df 27 | 28 | 29 | @task() 30 | def write_local(df: pd.DataFrame, color: str, dataset_file: str) -> Path: 31 | """Write DataFrame out locally as parquet file""" 32 | path = Path(f"data/{color}/{dataset_file}.parquet") 33 | df.to_parquet(path, compression="gzip") 34 | return path 35 | 36 | 37 | @task() 38 | def write_gcs(path: Path) -> None: 39 | """Upload local parquet file to GCS""" 40 | gcs_block = GcsBucket.load("zoom-gcs") 41 | gcs_block.upload_from_path(from_path=path, to_path=path) 42 | return 43 | 44 | 45 | @flow() 46 | def etl_web_to_gcs() -> None: 47 | """The main ETL function""" 48 | color = "yellow" 49 | year = 2021 50 | month = 1 51 | dataset_file = f"{color}_tripdata_{year}-{month:02}" 52 | dataset_url = f"https://github.com/DataTalksClub/nyc-tlc-data/releases/download/{color}/{dataset_file}.csv.gz" 53 | 54 | df = fetch(dataset_url) 55 | df_clean = clean(df) 56 | path = write_local(df_clean, color, dataset_file) 57 | write_gcs(path) 58 | 59 | 60 | if __name__ == "__main__": 61 | etl_web_to_gcs() 62 | -------------------------------------------------------------------------------- /flows/04_homework/el_gcs_to_bq.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | import pandas as pd 3 | from prefect import flow, task 4 | from prefect_gcp.cloud_storage import GcsBucket 5 | from prefect_gcp import GcpCredentials 6 | 7 | 8 | @task(retries=3) 9 | def extract_from_gcs(color: str, year: int, month: int) -> Path: 10 | """Download trip data from GCS""" 11 | gcs_path = f"data/{color}/{color}_tripdata_{year}-{month:02}.parquet" 12 | gcs_block = GcsBucket.load("zoom-gcs") 13 | gcs_block.get_directory(from_path=gcs_path, local_path=f"../data/") 14 | return Path(f"../data/{gcs_path}") 15 | 16 | 17 | @task() 18 | def read(path: Path) -> pd.DataFrame: 19 | """read the data into pandas""" 20 | df = pd.read_parquet(path) 21 | return df 22 | 23 | 24 | @task() 25 | def write_bq(df: pd.DataFrame) -> int: 26 | """Write DataFrame to BiqQuery""" 27 | 28 | gcp_credentials_block = GcpCredentials.load("zoom-gcp-creds") 29 | 30 | df.to_gbq( 31 | destination_table="dezoomcamp.rides", 32 | project_id="prefect-sbx-community-eng", 33 | credentials=gcp_credentials_block.get_credentials_from_service_account(), 34 | chunksize=500_000, 35 | if_exists="append", 36 | ) 37 | return len(df) 38 | 39 | 40 | @flow() 41 | def el_gcs_to_bq(year: int, month: int, color: str) -> None: 42 | """Main ETL flow to load data into Big Query""" 43 | 44 | path = extract_from_gcs(color, year, month) 45 | df = read(path) 46 | row_count = write_bq(df) 47 | return row_count 48 | 49 | 50 | @flow(log_prints=True) 51 | def el_parent_gcs_to_bq( 52 | months: list[int] = [1, 2], year: int = 2021, color: str = "yellow" 53 | ): 54 | """Main EL flow to load data into Big Query""" 55 | total_rows = 0 56 | 57 | for month in months: 58 | rows = el_gcs_to_bq(year, month, color) 59 | total_rows += rows 60 | 61 | print(total_rows) 62 | 63 | 64 | if __name__ == "__main__": 65 | el_parent_gcs_to_bq(months=[2, 3], year=2019, color="yellow") 66 | -------------------------------------------------------------------------------- /flows/01_start/ingest_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | import os 4 | import argparse 5 | from time import time 6 | import pandas as pd 7 | from sqlalchemy import create_engine 8 | 9 | 10 | def ingest_data(user, password, host, port, db, table_name, url): 11 | 12 | # the backup files are gzipped, and it's important to keep the correct extension 13 | # for pandas to be able to open the file 14 | if url.endswith('.csv.gz'): 15 | csv_name = 'yellow_tripdata_2021-01.csv.gz' 16 | else: 17 | csv_name = 'output.csv' 18 | 19 | os.system(f"wget {url} -O {csv_name}") 20 | postgres_url = f'postgresql://{user}:{password}@{host}:{port}/{db}' 21 | engine = create_engine(postgres_url) 22 | 23 | df_iter = pd.read_csv(csv_name, iterator=True, chunksize=100000) 24 | 25 | df = next(df_iter) 26 | 27 | df.tpep_pickup_datetime = pd.to_datetime(df.tpep_pickup_datetime) 28 | df.tpep_dropoff_datetime = pd.to_datetime(df.tpep_dropoff_datetime) 29 | 30 | df.head(n=0).to_sql(name=table_name, con=engine, if_exists='replace') 31 | 32 | df.to_sql(name=table_name, con=engine, if_exists='append') 33 | 34 | 35 | while True: 36 | 37 | try: 38 | t_start = time() 39 | 40 | df = next(df_iter) 41 | 42 | df.tpep_pickup_datetime = pd.to_datetime(df.tpep_pickup_datetime) 43 | df.tpep_dropoff_datetime = pd.to_datetime(df.tpep_dropoff_datetime) 44 | 45 | df.to_sql(name=table_name, con=engine, if_exists='append') 46 | 47 | t_end = time() 48 | 49 | print('inserted another chunk, took %.3f second' % (t_end - t_start)) 50 | 51 | except StopIteration: 52 | print("Finished ingesting data into the postgres database") 53 | break 54 | 55 | if __name__ == '__main__': 56 | user = "postgres" 57 | password = "admin" 58 | host = "localhost" 59 | port = "5433" 60 | db = "ny_taxi" 61 | table_name = "yellow_taxi_trips" 62 | csv_url = "https://github.com/DataTalksClub/nyc-tlc-data/releases/download/yellow/yellow_tripdata_2021-01.csv.gz" 63 | 64 | ingest_data(user, password, host, port, db, table_name, csv_url) -------------------------------------------------------------------------------- /flows/03_deployments/parameterized_flow.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | import pandas as pd 3 | from prefect import flow, task 4 | from prefect_gcp.cloud_storage import GcsBucket 5 | from random import randint 6 | from prefect.tasks import task_input_hash 7 | from datetime import timedelta 8 | 9 | 10 | @task(retries=3, cache_key_fn=task_input_hash, cache_expiration=timedelta(days=1)) 11 | def fetch(dataset_url: str) -> pd.DataFrame: 12 | """Read taxi data from web into pandas DataFrame""" 13 | # if randint(0, 1) > 0: 14 | # raise Exception 15 | 16 | df = pd.read_csv(dataset_url) 17 | return df 18 | 19 | 20 | @task(log_prints=True) 21 | def clean(df: pd.DataFrame) -> pd.DataFrame: 22 | """Fix dtype issues""" 23 | df["tpep_pickup_datetime"] = pd.to_datetime(df["tpep_pickup_datetime"]) 24 | df["tpep_dropoff_datetime"] = pd.to_datetime(df["tpep_dropoff_datetime"]) 25 | print(df.head(2)) 26 | print(f"columns: {df.dtypes}") 27 | print(f"rows: {len(df)}") 28 | return df 29 | 30 | 31 | @task() 32 | def write_local(df: pd.DataFrame, color: str, dataset_file: str) -> Path: 33 | """Write DataFrame out locally as parquet file""" 34 | path = Path(f"data/{color}/{dataset_file}.parquet") 35 | df.to_parquet(path, compression="gzip") 36 | return path 37 | 38 | 39 | @task() 40 | def write_gcs(path: Path) -> None: 41 | """Upload local parquet file to GCS""" 42 | gcs_block = GcsBucket.load("zoom-gcs") 43 | gcs_block.upload_from_path(from_path=path, to_path=path) 44 | return 45 | 46 | 47 | @flow() 48 | def etl_web_to_gcs(year: int, month: int, color: str) -> None: 49 | """The main ETL function""" 50 | dataset_file = f"{color}_tripdata_{year}-{month:02}" 51 | dataset_url = f"https://github.com/DataTalksClub/nyc-tlc-data/releases/download/{color}/{dataset_file}.csv.gz" 52 | 53 | df = fetch(dataset_url) 54 | df_clean = clean(df) 55 | path = write_local(df_clean, color, dataset_file) 56 | write_gcs(path) 57 | 58 | 59 | @flow() 60 | def etl_parent_flow( 61 | months: list[int] = [1, 2], year: int = 2021, color: str = "yellow" 62 | ): 63 | for month in months: 64 | etl_web_to_gcs(year, month, color) 65 | 66 | 67 | if __name__ == "__main__": 68 | color = "yellow" 69 | months = [1, 2, 3] 70 | year = 2021 71 | etl_parent_flow(months, year, color) 72 | -------------------------------------------------------------------------------- /flows/01_start/ingest_data_flow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | import os 4 | import argparse 5 | from time import time 6 | import pandas as pd 7 | from sqlalchemy import create_engine 8 | from prefect import flow, task 9 | from prefect.tasks import task_input_hash 10 | from datetime import timedelta 11 | from prefect_sqlalchemy import SqlAlchemyConnector 12 | 13 | 14 | @task(log_prints=True, tags=["extract"], cache_key_fn=task_input_hash, cache_expiration=timedelta(days=1)) 15 | def extract_data(url: str): 16 | # the backup files are gzipped, and it's important to keep the correct extension 17 | # for pandas to be able to open the file 18 | if url.endswith('.csv.gz'): 19 | csv_name = 'yellow_tripdata_2021-01.csv.gz' 20 | else: 21 | csv_name = 'output.csv' 22 | 23 | os.system(f"wget {url} -O {csv_name}") 24 | 25 | df_iter = pd.read_csv(csv_name, iterator=True, chunksize=100000) 26 | 27 | df = next(df_iter) 28 | 29 | df.tpep_pickup_datetime = pd.to_datetime(df.tpep_pickup_datetime) 30 | df.tpep_dropoff_datetime = pd.to_datetime(df.tpep_dropoff_datetime) 31 | 32 | return df 33 | 34 | @task(log_prints=True) 35 | def transform_data(df): 36 | print(f"pre: missing passenger count: {df['passenger_count'].isin([0]).sum()}") 37 | df = df[df['passenger_count'] != 0] 38 | print(f"post: missing passenger count: {df['passenger_count'].isin([0]).sum()}") 39 | return df 40 | 41 | @task(log_prints=True, retries=3) 42 | def load_data(table_name, df): 43 | 44 | connection_block = SqlAlchemyConnector.load("postgres-connector") 45 | with connection_block.get_connection(begin=False) as engine: 46 | df.head(n=0).to_sql(name=table_name, con=engine, if_exists='replace') 47 | df.to_sql(name=table_name, con=engine, if_exists='append') 48 | 49 | @flow(name="Subflow", log_prints=True) 50 | def log_subflow(table_name: str): 51 | print(f"Logging Subflow for: {table_name}") 52 | 53 | @flow(name="Ingest Data") 54 | def main_flow(table_name: str = "yellow_taxi_trips"): 55 | 56 | csv_url = "https://github.com/DataTalksClub/nyc-tlc-data/releases/download/yellow/yellow_tripdata_2021-01.csv.gz" 57 | log_subflow(table_name) 58 | raw_data = extract_data(csv_url) 59 | data = transform_data(raw_data) 60 | load_data(table_name, data) 61 | 62 | if __name__ == '__main__': 63 | main_flow(table_name = "yellow_trips") -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Engineering Zoomcamp 2023 Week 2 2 | ## Prefect 3 | 4 | This repo contains Python code to accompany the videos that show how to use Prefect for Data Engineering. We will create ETL workflows to extract, transform, and load your data. 5 | 6 | We will use Postgres and GCP's Google Cloud Storage and BigQuery. 7 | 8 | Prefect helps you observe and orchestrate your dataflows. 9 | 10 | # Setup 11 | 12 | ## Clone the repo 13 | 14 | Clone the repo locally. 15 | 16 | ## Install packages 17 | 18 | In a conda environment, install all package dependencies with 19 | 20 | ```bash 21 | pip install -r requirements.txt 22 | ``` 23 | ## Start the Prefect Orion server locally 24 | 25 | Create another window and activate your conda environment. Start the Orion API server locally with 26 | 27 | ```bash 28 | prefect orion start 29 | ``` 30 | 31 | ## Set up GCP 32 | 33 | - Log in to [GCP](https://cloud.google.com/) 34 | - Create a Project 35 | - Set up Cloud Storage 36 | - Set up BigQuery 37 | - Create a service account with the required policies to interact with both services 38 | 39 | ## Register the block types that come with prefect-gcp 40 | 41 | `prefect block register -m prefect_gcp` 42 | 43 | ## Create Prefect GCP blocks 44 | 45 | Create a *GCP Credentials* block in the UI. 46 | 47 | Paste your service account information from your JSON file into the *Service Account Info* block's field. 48 | 49 | ![img.png](images/img.png) 50 | 51 | Create a GCS Bucket block in UI 52 | 53 | Alternatively, create these blocks using code by following the templates in the [blocks](./blocks/) folder. 54 | 55 | ## Create flow code 56 | 57 | Write your Python functions and add `@flow` and `@task` decorators. 58 | 59 | Note: all code should be run from the top level of your folder to keep file paths consistent. 60 | 61 | ## Create deployments 62 | 63 | Create and apply your deployments. 64 | 65 | ## Run a deployment or create a schedule 66 | 67 | Run a deployment ad hoc from the CLI or UI. 68 | 69 | Or create a schedule from the UI or when you create your deployment. 70 | 71 | ## Start an agent 72 | 73 | Make sure your agent set up to poll the work queue you created when you made your deployment (*default* if you didn't specify a work queue). 74 | 75 | ## Later: create a Docker Image and use a DockerContainer infrastructure block 76 | 77 | Bake your flow code into a Docker image, create a DockerContainer, and your flow code in a Docker container. 78 | 79 | ## Optional: use Prefect Cloud for added capabilties 80 | Signup and use for free at https://app.prefect.cloud -------------------------------------------------------------------------------- /flows/04_homework/parameterized_flow_hw.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | import pandas as pd 3 | from prefect import flow, task 4 | from prefect_gcp.cloud_storage import GcsBucket 5 | from random import randint 6 | from prefect.tasks import task_input_hash 7 | from datetime import timedelta 8 | 9 | 10 | @task(retries=3) 11 | def fetch(dataset_url: str) -> pd.DataFrame: 12 | """Read taxi data from web into pandas DataFrame""" 13 | # if randint(0, 1) > 0: 14 | # raise Exception 15 | 16 | df = pd.read_csv(dataset_url) 17 | return df 18 | 19 | 20 | @task(log_prints=True) 21 | def clean(df: pd.DataFrame, color: str) -> pd.DataFrame: 22 | """Fix dtype issues""" 23 | if color == "yellow": 24 | df["tpep_pickup_datetime"] = pd.to_datetime(df["tpep_pickup_datetime"]) 25 | df["tpep_dropoff_datetime"] = pd.to_datetime(df["tpep_dropoff_datetime"]) 26 | else: 27 | df["lpep_pickup_datetime"] = pd.to_datetime(df["lpep_pickup_datetime"]) 28 | df["lpep_dropoff_datetime"] = pd.to_datetime(df["lpep_dropoff_datetime"]) 29 | print(df.head(2)) 30 | print(f"columns: {df.dtypes}") 31 | print(f"rows: {len(df)}") 32 | return df 33 | 34 | 35 | @task() 36 | def write_local(df: pd.DataFrame, color: str, dataset_file: str) -> Path: 37 | """Write DataFrame out locally as parquet file""" 38 | path = Path(f"data/{color}/{dataset_file}.parquet") 39 | df.to_parquet(path, compression="gzip") 40 | return path 41 | 42 | 43 | @task() 44 | def write_gcs(path: Path) -> None: 45 | """Upload local parquet file to GCS""" 46 | gcs_block = GcsBucket.load("zoom-gcs") 47 | gcs_block.upload_from_path(from_path=path, to_path=path) 48 | return 49 | 50 | 51 | @flow() 52 | def etl_web_to_gcs(year: int, month: int, color: str) -> None: 53 | """The main ETL function""" 54 | dataset_file = f"{color}_tripdata_{year}-{month:02}" 55 | dataset_url = f"https://github.com/DataTalksClub/nyc-tlc-data/releases/download/{color}/{dataset_file}.csv.gz" 56 | 57 | df = fetch(dataset_url) 58 | df_clean = clean( 59 | df, color 60 | ) # add color so can fix different column in green dataset 61 | path = write_local(df_clean, color, dataset_file) 62 | write_gcs(path) 63 | 64 | 65 | @flow() 66 | def etl_parent_flow( 67 | months: list[int] = [1, 2], year: int = 2021, color: str = "yellow" 68 | ): 69 | for month in months: 70 | etl_web_to_gcs(year, month, color) 71 | 72 | 73 | if __name__ == "__main__": 74 | color = "yellow" 75 | months = [2, 3] 76 | year = 2019 77 | etl_parent_flow(months, year, color) 78 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | .DS_Store 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | .pyre/ 128 | 129 | # Editors 130 | .idea/ 131 | .vscode/ 132 | .tmp/ 133 | *-deployment.yaml 134 | 135 | # Big files 136 | *.parquet 137 | *.csv 138 | *.json 139 | -------------------------------------------------------------------------------- /flows/03_deployments/README.md: -------------------------------------------------------------------------------- 1 | ## Transcript for Video 5 2 | 3 | Hi all! Today we’re going to be going over how to add Parameterization to your flows and create deployments. We’re going to be expanding on the etl_web_to_gsc.py so let’s go ahead and create a new file called parameterized_flow.py. If you’re following along with the github you can see this is the flows/03_deployments folder. 4 | And as a reminder this is building upon the existing flow and blocks that we can configured so if you haven’t already configured the GCS Bucket block, go back and make sure you do that first. 5 | 6 | So to start, let’s allow our flow to take parameters of year, month, and color: 7 | 8 | ``` 9 | @flow() 10 | def etl_web_to_gcs(year: int, month: int, color: str) -> None: 11 | """The main ETL function""" 12 | dataset_file = f"{color}_tripdata_{year}-{month:02}" 13 | dataset_url = f"https://github.com/DataTalksClub/nyc-tlc-data/releases/download/{color}/{dataset_file}.csv.gz" 14 | ``` 15 | 16 | 17 | Now let’s actually make a parent flow that will pass these parameters to the etl flow and we can set some defaults. This way I’m able to loop over a list of months and run the etl pipeline for each dataset. 18 | 19 | ``` 20 | @flow() 21 | def etl_parent_flow( 22 | months: list[int] = [1, 2], year: int = 2021, color: str = "yellow" 23 | ): 24 | for month in months: 25 | etl_web_to_gcs(year, month, color) 26 | ``` 27 | Once we have those parameters we can call the parent flow from main: 28 | 29 | ``` 30 | if __name__ == "__main__": 31 | color = "yellow" 32 | months = [1,2,3] 33 | year = 2021 34 | etl_parent_flow(months, year, color) 35 | ``` 36 | And just for good measure let’s add that caching key back to our fetch() function 37 | - add `from prefect.tasks import task_input_hash` 38 | - `@task(retries=3,cache_key_fn=task_input_hash, cache_expiration=timedelta(days=1))` 39 | 40 | Alright let’s go a head and run this and make sure we can see the output in the Cloud UI 41 | 42 | A deployment in Prefect is a server-side concept that encapsulates a flow, allowing it to be scheduled and triggered via the API. 43 | 44 | A flow can have multiple deployments and you can think of it as the container of metadata needed for the flow to be scheduled. This might be what type of infrastructure the flow will run on, or where the flow code is stored, maybe it’s scheduled or has certain parameters. 45 | 46 | There are two ways to create a deployment. One is using the CLI command and the other is with python. Jeff will show how to set up the deployment with Python in the next video so for now we are going to create one using the CLI. 47 | 48 | Inside your terminal we can type `prefect deployment build ./parameterized_flow.py:etl_parent_flow -n "Parameterized ETL"` 49 | 50 | Now you can see it created a yaml file with all our details. This is the metadata. We can adjust the parameters here or in the UI after we apply but let’s just do it here: 51 | - edit yaml with ` parameters: { "color": "yellow", "months" :[1, 2, 3], "year": 2021}` 52 | 53 | Now we need to apply the deployment: `prefect deployment apply etl_parent_flow-deployment.yaml` 54 | 55 | Here we can see the deployment in the UI, trigger a flow run, and you’ll notice this goes to late. That is because we are now using the API to trigger and schedule flow runs with this deployment instead of manually and we need to have an agent living in our execution environment (local) 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /flows/04_homework/homework.md: -------------------------------------------------------------------------------- 1 | ## Week 2 Homework 2 | 3 | The goal of this homework is to familiarise users with workflow orchestration and observation. 4 | 5 | 6 | ## Question 1. Load January 2020 data 7 | 8 | Using the `etl_web_to_gcs.py` flow that loads taxi data into GCS as a guide, create a flow that loads the green taxi CSV dataset for January 2020 into GCS and run it. Look at the logs to find out how many rows the dataset has. 9 | 10 | How many rows does that dataset have? 11 | 12 | * 447,770 13 | * 766,792 14 | * 299,234 15 | * 822,132 16 | 17 | 18 | ## Question 2. Scheduling with Cron 19 | 20 | Cron is a common scheduling specification for workflows. 21 | 22 | Using the flow in `etl_web_to_gcs.py`, create a deployment to run on the first of every month at 5am UTC. What’s the cron schedule for that? 23 | 24 | - `0 5 1 * *` 25 | - `0 0 5 1 *` 26 | - `5 * 1 0 *` 27 | - `* * 5 1 0` 28 | 29 | 30 | ## Question 3. Loading data to BigQuery 31 | 32 | Using `etl_gcs_to_bq.py` as a starting point, modify the script for extracting data from GCS and loading it into BigQuery. This new script should not fill or remove rows with missing values. (The script is really just doing the E and L parts of ETL). 33 | 34 | The main flow should print the total number of rows processed by the script. Set the flow decorator to log the print statement. 35 | 36 | Parametrize the entrypoint flow to accept a list of months, a year, and a taxi color. 37 | 38 | Make any other necessary changes to the code for it to function as required. 39 | 40 | Create a deployment for this flow to run in a local subprocess with local flow code storage (the defaults). 41 | 42 | Make sure you have the parquet data files for Yellow taxi data for Feb. 2019 and March 2019 loaded in GCS. Run your deployment to append this data to your BiqQuery table. How many rows did your flow code process? 43 | 44 | - 14,851,920 45 | - 12,282,990 46 | - 27,235,753 47 | - 11,338,483 48 | 49 | 50 | 51 | ## Question 4. Github Storage Block 52 | 53 | Using the `web_to_gcs` script from the videos as a guide, you want to store your flow code in a GitHub repository for collaboration with your team. Prefect can look in the GitHub repo to find your flow code and read it. Create a GitHub storage block from the UI or in Python code and use that in your Deployment instead of storing your flow code locally or baking your flow code into a Docker image. 54 | 55 | Note that you will have to push your code to GitHub, Prefect will not push it for you. 56 | 57 | Run your deployment in a local subprocess (the default if you don’t specify an infrastructure). Use the Green taxi data for the month of November 2020. 58 | 59 | How many rows were processed by the script? 60 | 61 | - 88,019 62 | - 192,297 63 | - 88,605 64 | - 190,225 65 | 66 | 67 | 68 | ## Question 5. Email or Slack notifications 69 | 70 | Q5. It’s often helpful to be notified when something with your dataflow doesn’t work as planned. Choose one of the options below for creating email or slack notifications. 71 | 72 | The hosted Prefect Cloud lets you avoid running your own server and has Automations that allow you to get notifications when certain events occur or don’t occur. 73 | 74 | Create a free forever Prefect Cloud account at app.prefect.cloud and connect your workspace to it following the steps in the UI when you sign up. 75 | 76 | Set up an Automation that will send yourself an email when a flow run completes. Run the deployment used in Q4 for the Green taxi data for April 2019. Check your email to see the notification. 77 | 78 | Alternatively, use a Prefect Cloud Automation or a self-hosted Orion server Notification to get notifications in a Slack workspace via an incoming webhook. 79 | 80 | Join my temporary Slack workspace with [this link](https://join.slack.com/t/temp-notify/shared_invite/zt-1odklt4wh-hH~b89HN8MjMrPGEaOlxIw). 400 people can use this link and it expires in 90 days. 81 | 82 | In the Prefect Cloud UI create an [Automation](https://docs.prefect.io/ui/automations) or in the Prefect Orion UI create a [Notification](https://docs.prefect.io/ui/notifications/) to send a Slack message when a flow run enters a Completed state. Here is the Webhook URL to use: https://hooks.slack.com/services/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 83 | 84 | Test the functionality. 85 | 86 | Alternatively, you can grab the webhook URL from your own Slack workspace and Slack App that you create. 87 | 88 | 89 | How many rows were processed by the script? 90 | 91 | - `125,268` 92 | - `377,922` 93 | - `728,390` 94 | - `514,392` 95 | 96 | 97 | ## Question 6. Secrets 98 | 99 | Prefect Secret blocks provide secure, encrypted storage in the database and obfuscation in the UI. Create a secret block in the UI that stores a fake 10-digit password to connect to a third-party service. Once you’ve created your block in the UI, how many characters are shown as asterisks (*) on the next page of the UI? 100 | 101 | - 5 102 | - 6 103 | - 8 104 | - 10 105 | 106 | 107 | ## Submitting the solutions 108 | 109 | * Form for submitting: TODO 110 | * You can submit your homework multiple times. In this case, only the last submission will be used. 111 | 112 | Deadline: 6 February (Monday), 22:00 CET 113 | 114 | 115 | ## Solution 116 | 117 | We will publish the solution here 118 | -------------------------------------------------------------------------------- /flows/01_start/README.md: -------------------------------------------------------------------------------- 1 | ## Transcript for Video 2 2 | 3 | In this session, we are going to take a look at a basic python script that pulls the yellow taxi data into a postgres db and then transforms that script to be orchestrated with Prefect. 4 | 5 | Prefect is the modern open source dataflow automation platform that will allow us to add observability and orchestration by utilizing python to write code as workflows to build,run and monitor pipelines at scale. 6 | 7 | First lets create a conda environment 8 | 9 | `conda create -n zoom python=3.9` 10 | 11 | You can install the requirements found in requirements.txt ` pip install -r requirements.txt` or install Prefect `pip install prefect -U` 12 | 13 | Now that we have everything install, you can see that this script is going to call a function called ingest_data which takes the parameters for a postgres db connection and will pull the data specified as a parameter and then load it into the postgres db. 14 | 15 | I’m going to be using pgAdmin4, and have already created the db named ny_taxi. Feel free to use whatever tool you are most familiar with to query postgres. 16 | 17 | Let’s go ahead and run this script. 18 | 19 | `python ingest_data.py` 20 | 21 | Alright looking in pgAdmin4, we can see that the data ingested into the postgres db. This is great but I had to manually trigger this python script. Using a workflow orchestration tool will allow me to add a scheduler so that I won’t have to trigger this script manually anymore. Additionally, I’ll get all the functionality that comes with workflow orchestation such as visibility, add resilience to the dataflow with automatic retries or caching and more. 22 | 23 | Let’s transform this into a Prefect flow. A flow is the most basic Prefect object that is a container for workflow logic and allows you to interact and understand the state of the workflow. Flows are like functions, they take inputs, preform work, and return an output. We can start by using the @flow decorator to a main_flow function. 24 | 25 | - import prefect with `from prefect import flow, task` 26 | - add `@flow(name="Ingest Flow")` above main() function 27 | 28 | Flows contain tasks so let’s transform ingest_data into a task by adding the @task decorator. Tasks are not required for flows but tasks are special because they receive metadata about upstream dependencies and the state of those dependencies before the function is run, which gives you the opportunity to have a task wait on the completion of another task before executing. 29 | 30 | - add `@task(log_prints=True, retries=3)` above ingest_data() function 31 | 32 | Now let’s run the ingest_data.py as a Prefect flow. 33 | 34 | `python ingest_data.py` 35 | 36 | Awesome, so that just ran the script as a flow. Alright let’s actually simplify this script and transform it into a extract and transform before we load the data into the postgres db. 37 | 38 | I’m going to start by breaking apart the large ingest_data function into multiple functions so that we can get more visibility into the tasks that are running or potentially causing failures. 39 | 40 | Let’s create a new task called extract data that will take the url for the csv and the task will actually return the results. Since this is pulling data from external my system (something I may not control) I want to add automatic retries and also add a caching so that if this task has already been run, it will not need to run again. 41 | 42 | - import `from prefect.tasks import task_input_hash` 43 | - extract_data() code: 44 | ``` 45 | @task(log_prints=True, tags=["extract"], cache_key_fn=task_input_hash, cache_expiration=timedelta(days=1)) 46 | def extract_data(url: str): 47 | # the backup files are gzipped, and it's important to keep the correct extension 48 | # for pandas to be able to open the file 49 | if url.endswith('.csv.gz'): 50 | csv_name = 'yellow_tripdata_2021-01.csv.gz' 51 | else: 52 | csv_name = 'output.csv' 53 | 54 | os.system(f"wget {url} -O {csv_name}") 55 | 56 | df_iter = pd.read_csv(csv_name, iterator=True, chunksize=100000) 57 | 58 | df = next(df_iter) 59 | 60 | df.tpep_pickup_datetime = pd.to_datetime(df.tpep_pickup_datetime) 61 | df.tpep_dropoff_datetime = pd.to_datetime(df.tpep_dropoff_datetime) 62 | 63 | return df 64 | ``` 65 | 66 | Now that we have moved that logic into it’s own task, let’s call that task from the flow. 67 | 68 | Next, If you look at the data in ny_taxi, you’ll see that on row 4, there is a passenger count of 0 so let’s do a transformation step to cleanse the data before we load the data to postgres. I’ll create a new task called transform_data for this. Notice how I can easily pass the dataframe to the following task. 69 | 70 | - transform_data() function: 71 | ``` 72 | @task(log_prints=True) 73 | def transform_data(df): 74 | print(f"pre: missing passenger count: {df['passenger_count'].isin([0]).sum()}") 75 | df = df[df['passenger_count'] != 0] 76 | print(f"post: missing passenger count: {df['passenger_count'].isin([0]).sum()}") 77 | return df 78 | ``` 79 | Lastly, let’s actually simplify the original ingest_data() function and rename this to load_data() 80 | 81 | ``` 82 | @task(log_prints=True, retries=3) 83 | def load_data(user, password, host, port, db, table_name, df): 84 | postgres_url = f'postgresql://{user}:{password}@{host}:{port}/{db}' 85 | engine = create_engine(postgresql_url) 86 | 87 | df.head(n=0).to_sql(name=table_name, con=engine, if_exists='replace') 88 | df.to_sql(name=table)name, con=engine, if_exists='append') 89 | ``` 90 | main() function now looks like: 91 | ``` 92 | @flow(name="Ingest Flow") 93 | def main(user, password, host, port, db, table_name, csv_url): 94 | raw_data = extract_data(csv_url) 95 | data = transform_data(raw_data) 96 | load_data(user, password, host, port, db, table_name, data) 97 | ``` 98 | Let’s clean the db and run the flow again with `drop table yellow_taxi_trips` 99 | 100 | Now let's run our flow `python ingest_data.py` 101 | 102 | And if we look at the DB, we can see there are no more passenger counts of 0. 103 | 104 | There’s a lot more we can add by sprinkling in Prefect to our flow. We could parameterize the flow to take a table name so that we could change the table name loaded each time the flow was run. 105 | 106 | ``` 107 | @flow(name="Ingest Data") 108 | def main(table_name: str): 109 | user = "postgres" 110 | password = "admin" 111 | host = "localhost" 112 | port = "5433" 113 | db = "ny_taxi" 114 | table_name = "yellow_taxi_trips" 115 | csv_url = "https://github.com/DataTalksClub/nyc-tlc-data/releases/download/yellow/yellow_tripdata_2021-01.csv.gz" 116 | 117 | raw_data = extract_data(csv_url) 118 | data = transform_data(raw_data) 119 | load_data(user, password, host, port, db, table_name, data) 120 | 121 | if __name__ == "__main__": 122 | main("yellow_taxi_trips") 123 | ``` 124 | 125 | We could add a subflow. There’s a lot more you can do but here are just a few examples. 126 | 127 | add function log_subflow(): 128 | ``` 129 | @flow(name="Subflow", log_prints=True) 130 | def log_subflow(table_name : str): 131 | print(f"Logging Subflow for {table_name}") 132 | ``` 133 | 134 | add newline `log_subflow(table_name)` to the main() flow 135 | 136 | Alright let’s run the flow and then open the open source UI to visual. 137 | 138 | `python ingest_data.py` 139 | `python orion start` 140 | 141 | This should default but if your having problem or just want to make sure you set the prefect config to point to the api URL. This is especially important if you are going to host the Url somewhere else and need to change the url for the api that your flows are communicating with. 142 | 143 | `prefect config set PREFECT_API_URL="http://127.0.0.1:4200/api"` 144 | 145 | 146 | Alright opening up localhost we can see the Prefect UI, which gives us a nice dashboard to see all of our flow run history. 147 | 148 | If we run a flow again we can see in our terminal and the look at the UI and can see that same flow name. 149 | 150 | A quick navigation lets us dive into the logs of that flow run, navigate around. You’ll notice over on the side we have Deployments, Workqueues Blocks, Notifications, and TaskRun Concurrency. 151 | 152 | We will get to Deployments and Workques in later video but I want to quickly touch on Blocks, Notifications and TaskRun Concurrency. 153 | 154 | Task Run concurrency can be configured on tasks by adding a tag to the task and then setting a limit through a CLI command. 155 | 156 | Notifications are important so that we know when something has failed or is wrong with our system. Instead of having to monitor our dashboard frequently, we can get a notification when something goes wrong and needs to be investigated. 157 | 158 | Blocks are my personal favorite feature of Prefect. Blocks are a primitive within Prefect that enable the storage of configuration and provide an interface with interacting with external systems. There are several different types of blocks you can build, and you can even create your own. Block names are immutable so they can be reused across multiple flows. Blocks can also build upon blocks or be installed as part of Intergration collection which is prebuilt tasks and blocks that are pip installable. For example, a lot of users use the SqlAlchemy 159 | 160 | Let’s actually take our postgres configuration and store that in a block 161 | - pip install SQL Alchemy 162 | - Create a SQL Alchemy Connector block and place all configuration in there 163 | - Change the flow code: 164 | - add `from prefect_sqlalchemy import SqlAlchemyConnector` 165 | - change load_data() function: 166 | ``` 167 | @task(log_prints=True, retries=3) 168 | def load_data(table_name, df): 169 | 170 | connection_block = SqlAlchemyConnector.load("postgres-connector") 171 | with connection_block.get_connection(begin=False) as engine: 172 | df.head(n=0).to_sql(name=table_name, con=engine, if_exists='replace') 173 | df.to_sql(name=table_name, con=engine, if_exists='append') 174 | 175 | ``` 176 | 177 | Alright run the flow and let’s see if it was successful in the UI. 178 | 179 | 180 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /exploration/clean_taxi.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "84582838-6795-46ae-a5de-ded5c977028d", 6 | "metadata": {}, 7 | "source": [ 8 | "### A little inspection and cleanup of taxi data\n", 9 | "\n", 10 | "Jeff Hale" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 48, 16 | "id": "c907d49f-2d8c-44f2-bba6-8fb180d35ca7", 17 | "metadata": {}, 18 | "outputs": [], 19 | "source": [ 20 | "import pandas as pd" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": 49, 26 | "id": "b4b1cb2b-602b-4955-88a7-ddd3ab16b827", 27 | "metadata": {}, 28 | "outputs": [ 29 | { 30 | "name": "stderr", 31 | "output_type": "stream", 32 | "text": [ 33 | "/var/folders/8q/819stl696vz3fxzpbnnsp2540000gn/T/ipykernel_5270/1637784685.py:1: DtypeWarning: Columns (6) have mixed types. Specify dtype option on import or set low_memory=False.\n", 34 | " df= pd.read_csv(\"https://github.com/DataTalksClub/nyc-tlc-data/releases/download/yellow/yellow_tripdata_2021-06.csv.gz\")\n" 35 | ] 36 | }, 37 | { 38 | "data": { 39 | "text/html": [ 40 | "
\n", 41 | "\n", 54 | "\n", 55 | " \n", 56 | " \n", 57 | " \n", 58 | " \n", 59 | " \n", 60 | " \n", 61 | " \n", 62 | " \n", 63 | " \n", 64 | " \n", 65 | " \n", 66 | " \n", 67 | " \n", 68 | " \n", 69 | " \n", 70 | " \n", 71 | " \n", 72 | " \n", 73 | " \n", 74 | " \n", 75 | " \n", 76 | " \n", 77 | " \n", 78 | " \n", 79 | " \n", 80 | " \n", 81 | " \n", 82 | " \n", 83 | " \n", 84 | " \n", 85 | " \n", 86 | " \n", 87 | " \n", 88 | " \n", 89 | " \n", 90 | " \n", 91 | " \n", 92 | " \n", 93 | " \n", 94 | " \n", 95 | " \n", 96 | " \n", 97 | " \n", 98 | " \n", 99 | " \n", 100 | " \n", 101 | " \n", 102 | " \n", 103 | " \n", 104 | " \n", 105 | " \n", 106 | " \n", 107 | " \n", 108 | " \n", 109 | " \n", 110 | " \n", 111 | " \n", 112 | " \n", 113 | " \n", 114 | " \n", 115 | " \n", 116 | " \n", 117 | " \n", 118 | " \n", 119 | " \n", 120 | " \n", 121 | " \n", 122 | " \n", 123 | " \n", 124 | " \n", 125 | " \n", 126 | " \n", 127 | " \n", 128 | " \n", 129 | " \n", 130 | " \n", 131 | " \n", 132 | " \n", 133 | " \n", 134 | " \n", 135 | " \n", 136 | " \n", 137 | " \n", 138 | " \n", 139 | " \n", 140 | " \n", 141 | " \n", 142 | " \n", 143 | " \n", 144 | " \n", 145 | " \n", 146 | " \n", 147 | " \n", 148 | " \n", 149 | " \n", 150 | " \n", 151 | " \n", 152 | " \n", 153 | " \n", 154 | " \n", 155 | " \n", 156 | " \n", 157 | " \n", 158 | " \n", 159 | " \n", 160 | " \n", 161 | " \n", 162 | " \n", 163 | " \n", 164 | " \n", 165 | " \n", 166 | " \n", 167 | " \n", 168 | " \n", 169 | " \n", 170 | " \n", 171 | " \n", 172 | " \n", 173 | " \n", 174 | " \n", 175 | " \n", 176 | " \n", 177 | " \n", 178 | " \n", 179 | " \n", 180 | " \n", 181 | " \n", 182 | " \n", 183 | " \n", 184 | " \n", 185 | " \n", 186 | " \n", 187 | " \n", 188 | " \n", 189 | " \n", 190 | " \n", 191 | " \n", 192 | " \n", 193 | " \n", 194 | " \n", 195 | " \n", 196 | " \n", 197 | " \n", 198 | " \n", 199 | " \n", 200 | " \n", 201 | " \n", 202 | " \n", 203 | " \n", 204 | " \n", 205 | " \n", 206 | " \n", 207 | " \n", 208 | " \n", 209 | " \n", 210 | " \n", 211 | " \n", 212 | " \n", 213 | " \n", 214 | " \n", 215 | " \n", 216 | " \n", 217 | " \n", 218 | " \n", 219 | " \n", 220 | " \n", 221 | " \n", 222 | " \n", 223 | " \n", 224 | " \n", 225 | " \n", 226 | " \n", 227 | " \n", 228 | " \n", 229 | " \n", 230 | " \n", 231 | " \n", 232 | " \n", 233 | " \n", 234 | " \n", 235 | " \n", 236 | " \n", 237 | " \n", 238 | " \n", 239 | " \n", 240 | " \n", 241 | " \n", 242 | " \n", 243 | " \n", 244 | " \n", 245 | " \n", 246 | " \n", 247 | " \n", 248 | " \n", 249 | " \n", 250 | " \n", 251 | " \n", 252 | " \n", 253 | " \n", 254 | " \n", 255 | " \n", 256 | " \n", 257 | " \n", 258 | " \n", 259 | " \n", 260 | " \n", 261 | " \n", 262 | " \n", 263 | " \n", 264 | " \n", 265 | " \n", 266 | " \n", 267 | " \n", 268 | " \n", 269 | " \n", 270 | " \n", 271 | " \n", 272 | " \n", 273 | " \n", 274 | " \n", 275 | " \n", 276 | " \n", 277 | " \n", 278 | " \n", 279 | " \n", 280 | " \n", 281 | " \n", 282 | " \n", 283 | " \n", 284 | " \n", 285 | " \n", 286 | " \n", 287 | " \n", 288 | " \n", 289 | " \n", 290 | " \n", 291 | " \n", 292 | " \n", 293 | " \n", 294 | " \n", 295 | " \n", 296 | " \n", 297 | " \n", 298 | " \n", 299 | " \n", 300 | " \n", 301 | " \n", 302 | " \n", 303 | " \n", 304 | " \n", 305 | " \n", 306 | " \n", 307 | " \n", 308 | " \n", 309 | " \n", 310 | " \n", 311 | "
VendorIDtpep_pickup_datetimetpep_dropoff_datetimepassenger_counttrip_distanceRatecodeIDstore_and_fwd_flagPULocationIDDOLocationIDpayment_typefare_amountextramta_taxtip_amounttolls_amountimprovement_surchargetotal_amountcongestion_surcharge
01.02021-06-01 00:13:262021-06-01 00:17:141.00.901.0N186501.05.003.000.52.200.000.311.002.5
11.02021-06-01 00:32:232021-06-01 01:07:041.023.001.0N132182.061.501.750.50.006.550.370.600.0
21.02021-06-01 00:12:152021-06-01 00:15:280.00.901.0N138702.05.001.750.50.000.000.37.550.0
31.02021-06-01 00:35:002021-06-01 00:53:170.011.201.0N1381891.031.501.750.58.500.000.342.550.0
42.02021-06-01 00:31:012021-06-01 00:52:271.09.491.0N1381421.028.500.500.57.776.550.347.872.5
.........................................................
2834259NaN2021-06-23 07:33:562021-06-23 07:42:23NaN1.60NaNNaN50164NaN8.000.000.51.130.000.312.432.5
2834260NaN2021-06-23 07:19:002021-06-23 08:03:00NaN15.25NaNNaN123162NaN43.912.750.50.006.550.354.010.0
2834261NaN2021-06-23 07:06:582021-06-23 08:06:42NaN6.27NaNNaN265181NaN39.980.000.50.000.000.340.780.0
2834262NaN2021-06-23 07:06:382021-06-23 08:06:15NaN9.13NaNNaN26525NaN42.030.000.50.000.000.342.830.0
2834263NaN2021-06-23 07:35:002021-06-23 08:05:00NaN9.40NaNNaN9590NaN29.422.750.50.006.550.339.520.0
\n", 312 | "

2834264 rows × 18 columns

\n", 313 | "
" 314 | ], 315 | "text/plain": [ 316 | " VendorID tpep_pickup_datetime tpep_dropoff_datetime passenger_count \\\n", 317 | "0 1.0 2021-06-01 00:13:26 2021-06-01 00:17:14 1.0 \n", 318 | "1 1.0 2021-06-01 00:32:23 2021-06-01 01:07:04 1.0 \n", 319 | "2 1.0 2021-06-01 00:12:15 2021-06-01 00:15:28 0.0 \n", 320 | "3 1.0 2021-06-01 00:35:00 2021-06-01 00:53:17 0.0 \n", 321 | "4 2.0 2021-06-01 00:31:01 2021-06-01 00:52:27 1.0 \n", 322 | "... ... ... ... ... \n", 323 | "2834259 NaN 2021-06-23 07:33:56 2021-06-23 07:42:23 NaN \n", 324 | "2834260 NaN 2021-06-23 07:19:00 2021-06-23 08:03:00 NaN \n", 325 | "2834261 NaN 2021-06-23 07:06:58 2021-06-23 08:06:42 NaN \n", 326 | "2834262 NaN 2021-06-23 07:06:38 2021-06-23 08:06:15 NaN \n", 327 | "2834263 NaN 2021-06-23 07:35:00 2021-06-23 08:05:00 NaN \n", 328 | "\n", 329 | " trip_distance RatecodeID store_and_fwd_flag PULocationID \\\n", 330 | "0 0.90 1.0 N 186 \n", 331 | "1 23.00 1.0 N 132 \n", 332 | "2 0.90 1.0 N 138 \n", 333 | "3 11.20 1.0 N 138 \n", 334 | "4 9.49 1.0 N 138 \n", 335 | "... ... ... ... ... \n", 336 | "2834259 1.60 NaN NaN 50 \n", 337 | "2834260 15.25 NaN NaN 123 \n", 338 | "2834261 6.27 NaN NaN 265 \n", 339 | "2834262 9.13 NaN NaN 265 \n", 340 | "2834263 9.40 NaN NaN 95 \n", 341 | "\n", 342 | " DOLocationID payment_type fare_amount extra mta_tax tip_amount \\\n", 343 | "0 50 1.0 5.00 3.00 0.5 2.20 \n", 344 | "1 18 2.0 61.50 1.75 0.5 0.00 \n", 345 | "2 70 2.0 5.00 1.75 0.5 0.00 \n", 346 | "3 189 1.0 31.50 1.75 0.5 8.50 \n", 347 | "4 142 1.0 28.50 0.50 0.5 7.77 \n", 348 | "... ... ... ... ... ... ... \n", 349 | "2834259 164 NaN 8.00 0.00 0.5 1.13 \n", 350 | "2834260 162 NaN 43.91 2.75 0.5 0.00 \n", 351 | "2834261 181 NaN 39.98 0.00 0.5 0.00 \n", 352 | "2834262 25 NaN 42.03 0.00 0.5 0.00 \n", 353 | "2834263 90 NaN 29.42 2.75 0.5 0.00 \n", 354 | "\n", 355 | " tolls_amount improvement_surcharge total_amount \\\n", 356 | "0 0.00 0.3 11.00 \n", 357 | "1 6.55 0.3 70.60 \n", 358 | "2 0.00 0.3 7.55 \n", 359 | "3 0.00 0.3 42.55 \n", 360 | "4 6.55 0.3 47.87 \n", 361 | "... ... ... ... \n", 362 | "2834259 0.00 0.3 12.43 \n", 363 | "2834260 6.55 0.3 54.01 \n", 364 | "2834261 0.00 0.3 40.78 \n", 365 | "2834262 0.00 0.3 42.83 \n", 366 | "2834263 6.55 0.3 39.52 \n", 367 | "\n", 368 | " congestion_surcharge \n", 369 | "0 2.5 \n", 370 | "1 0.0 \n", 371 | "2 0.0 \n", 372 | "3 0.0 \n", 373 | "4 2.5 \n", 374 | "... ... \n", 375 | "2834259 2.5 \n", 376 | "2834260 0.0 \n", 377 | "2834261 0.0 \n", 378 | "2834262 0.0 \n", 379 | "2834263 0.0 \n", 380 | "\n", 381 | "[2834264 rows x 18 columns]" 382 | ] 383 | }, 384 | "execution_count": 49, 385 | "metadata": {}, 386 | "output_type": "execute_result" 387 | } 388 | ], 389 | "source": [ 390 | "df= pd.read_csv(\"https://github.com/DataTalksClub/nyc-tlc-data/releases/download/yellow/yellow_tripdata_2021-06.csv.gz\")\n", 391 | "df" 392 | ] 393 | }, 394 | { 395 | "cell_type": "markdown", 396 | "id": "581ea1ac", 397 | "metadata": {}, 398 | "source": [ 399 | "We should fix the mixed dtypes" 400 | ] 401 | }, 402 | { 403 | "cell_type": "code", 404 | "execution_count": 50, 405 | "id": "d914321f-905e-45cc-9d8a-52b042831d30", 406 | "metadata": {}, 407 | "outputs": [ 408 | { 409 | "data": { 410 | "text/plain": [ 411 | "VendorID float64\n", 412 | "tpep_pickup_datetime object\n", 413 | "tpep_dropoff_datetime object\n", 414 | "passenger_count float64\n", 415 | "trip_distance float64\n", 416 | "RatecodeID float64\n", 417 | "store_and_fwd_flag object\n", 418 | "PULocationID int64\n", 419 | "DOLocationID int64\n", 420 | "payment_type float64\n", 421 | "fare_amount float64\n", 422 | "extra float64\n", 423 | "mta_tax float64\n", 424 | "tip_amount float64\n", 425 | "tolls_amount float64\n", 426 | "improvement_surcharge float64\n", 427 | "total_amount float64\n", 428 | "congestion_surcharge float64\n", 429 | "dtype: object" 430 | ] 431 | }, 432 | "execution_count": 50, 433 | "metadata": {}, 434 | "output_type": "execute_result" 435 | } 436 | ], 437 | "source": [ 438 | "df.dtypes" 439 | ] 440 | }, 441 | { 442 | "cell_type": "markdown", 443 | "id": "5fc5d820-26c5-457d-bd2e-188bfd1079d8", 444 | "metadata": {}, 445 | "source": [ 446 | "## Transforms\n", 447 | "### Change the date columns from string to datetime format" 448 | ] 449 | }, 450 | { 451 | "cell_type": "code", 452 | "execution_count": 51, 453 | "id": "44e7577d-f544-4631-a910-3bed509a2b53", 454 | "metadata": {}, 455 | "outputs": [ 456 | { 457 | "data": { 458 | "text/plain": [ 459 | "VendorID float64\n", 460 | "tpep_pickup_datetime datetime64[ns]\n", 461 | "tpep_dropoff_datetime datetime64[ns]\n", 462 | "passenger_count float64\n", 463 | "trip_distance float64\n", 464 | "RatecodeID float64\n", 465 | "store_and_fwd_flag object\n", 466 | "PULocationID int64\n", 467 | "DOLocationID int64\n", 468 | "payment_type float64\n", 469 | "fare_amount float64\n", 470 | "extra float64\n", 471 | "mta_tax float64\n", 472 | "tip_amount float64\n", 473 | "tolls_amount float64\n", 474 | "improvement_surcharge float64\n", 475 | "total_amount float64\n", 476 | "congestion_surcharge float64\n", 477 | "dtype: object" 478 | ] 479 | }, 480 | "execution_count": 51, 481 | "metadata": {}, 482 | "output_type": "execute_result" 483 | } 484 | ], 485 | "source": [ 486 | "df['tpep_pickup_datetime'] = pd.to_datetime(df['tpep_pickup_datetime'])\n", 487 | "df['tpep_dropoff_datetime'] = pd.to_datetime(df['tpep_dropoff_datetime'])\n", 488 | "df.dtypes" 489 | ] 490 | }, 491 | { 492 | "cell_type": "code", 493 | "execution_count": 52, 494 | "id": "91e55c42-561a-4e0c-bea8-9150fe2d0200", 495 | "metadata": {}, 496 | "outputs": [ 497 | { 498 | "data": { 499 | "text/html": [ 500 | "
\n", 501 | "\n", 514 | "\n", 515 | " \n", 516 | " \n", 517 | " \n", 518 | " \n", 519 | " \n", 520 | " \n", 521 | " \n", 522 | " \n", 523 | " \n", 524 | " \n", 525 | " \n", 526 | " \n", 527 | " \n", 528 | " \n", 529 | " \n", 530 | " \n", 531 | " \n", 532 | " \n", 533 | " \n", 534 | " \n", 535 | " \n", 536 | " \n", 537 | " \n", 538 | " \n", 539 | " \n", 540 | " \n", 541 | " \n", 542 | " \n", 543 | " \n", 544 | " \n", 545 | " \n", 546 | " \n", 547 | " \n", 548 | " \n", 549 | " \n", 550 | " \n", 551 | " \n", 552 | " \n", 553 | " \n", 554 | " \n", 555 | " \n", 556 | " \n", 557 | " \n", 558 | " \n", 559 | " \n", 560 | " \n", 561 | " \n", 562 | " \n", 563 | " \n", 564 | " \n", 565 | " \n", 566 | " \n", 567 | " \n", 568 | " \n", 569 | " \n", 570 | " \n", 571 | " \n", 572 | " \n", 573 | " \n", 574 | " \n", 575 | " \n", 576 | " \n", 577 | " \n", 578 | " \n", 579 | " \n", 580 | " \n", 581 | " \n", 582 | "
VendorIDtpep_pickup_datetimetpep_dropoff_datetimepassenger_counttrip_distanceRatecodeIDstore_and_fwd_flagPULocationIDDOLocationIDpayment_typefare_amountextramta_taxtip_amounttolls_amountimprovement_surchargetotal_amountcongestion_surcharge
01.02021-06-01 00:13:262021-06-01 00:17:141.00.91.0N186501.05.03.000.52.20.000.311.02.5
11.02021-06-01 00:32:232021-06-01 01:07:041.023.01.0N132182.061.51.750.50.06.550.370.60.0
\n", 583 | "
" 584 | ], 585 | "text/plain": [ 586 | " VendorID tpep_pickup_datetime tpep_dropoff_datetime passenger_count \\\n", 587 | "0 1.0 2021-06-01 00:13:26 2021-06-01 00:17:14 1.0 \n", 588 | "1 1.0 2021-06-01 00:32:23 2021-06-01 01:07:04 1.0 \n", 589 | "\n", 590 | " trip_distance RatecodeID store_and_fwd_flag PULocationID DOLocationID \\\n", 591 | "0 0.9 1.0 N 186 50 \n", 592 | "1 23.0 1.0 N 132 18 \n", 593 | "\n", 594 | " payment_type fare_amount extra mta_tax tip_amount tolls_amount \\\n", 595 | "0 1.0 5.0 3.00 0.5 2.2 0.00 \n", 596 | "1 2.0 61.5 1.75 0.5 0.0 6.55 \n", 597 | "\n", 598 | " improvement_surcharge total_amount congestion_surcharge \n", 599 | "0 0.3 11.0 2.5 \n", 600 | "1 0.3 70.6 0.0 " 601 | ] 602 | }, 603 | "execution_count": 52, 604 | "metadata": {}, 605 | "output_type": "execute_result" 606 | } 607 | ], 608 | "source": [ 609 | "df.head(2)" 610 | ] 611 | }, 612 | { 613 | "cell_type": "markdown", 614 | "id": "a58fb673", 615 | "metadata": {}, 616 | "source": [ 617 | "Because there are missing values, pandas converts to a float. We could have specified we wanted nullable integer dtype, but float is fine." 618 | ] 619 | }, 620 | { 621 | "cell_type": "markdown", 622 | "id": "6185d168-1006-48a8-9aa3-b451986173f8", 623 | "metadata": {}, 624 | "source": [ 625 | "### Write out cleaned file" 626 | ] 627 | }, 628 | { 629 | "cell_type": "code", 630 | "execution_count": 14, 631 | "id": "38a43e21-f9b9-44e1-9e30-2aa25e432783", 632 | "metadata": {}, 633 | "outputs": [], 634 | "source": [ 635 | "df.to_parquet(\"2022-07_yellow_cleaned.parquet\", compression='gzip')" 636 | ] 637 | }, 638 | { 639 | "cell_type": "markdown", 640 | "id": "757cf1fd", 641 | "metadata": {}, 642 | "source": [ 643 | "The end" 644 | ] 645 | } 646 | ], 647 | "metadata": { 648 | "kernelspec": { 649 | "display_name": "base", 650 | "language": "python", 651 | "name": "python3" 652 | }, 653 | "language_info": { 654 | "codemirror_mode": { 655 | "name": "ipython", 656 | "version": 3 657 | }, 658 | "file_extension": ".py", 659 | "mimetype": "text/x-python", 660 | "name": "python", 661 | "nbconvert_exporter": "python", 662 | "pygments_lexer": "ipython3", 663 | "version": "3.10.8" 664 | }, 665 | "vscode": { 666 | "interpreter": { 667 | "hash": "bdb908cc57355dbb5a003d7838c8989df6128b2109ab46b289dd5188981510ed" 668 | } 669 | } 670 | }, 671 | "nbformat": 4, 672 | "nbformat_minor": 5 673 | } 674 | --------------------------------------------------------------------------------