Data Preparation - Hurricane analysis, part 1/3¶
Introduction¶
Hurricanes are large swirling storms that produce winds of speeds 74
miles per hour (119
kmph) or higher. When hurricanes make a landfall, they produce heavy rainfall, cause storm surges and intense flooding. Often hurricanes strike places that are dense in population, causing devastating amounts of death and destruction throughout the world.
Since the recent past, agencies such as the National Hurricane Center have been collecting quantitative data about hurricanes. In this study we use meteorological data of hurricanes recorded in the past 169
years to analyze their location, intensity and investigate if there are any statistically significant trends. We also analyze the places most affected by hurricanes and what their demographic make up is. We conclude by citing relevant articles that draw similar conclusions.
This notebook covers part 1 of this study. In this notebook, we:
- download data from NCEI portal
- do extensive pre-processing in the form of clearing headers, merging redundant columns
- aggregate the observations into hurricane tracks.
Note: To run this sample, you need a few extra libraries in your conda environment. If you don't have the libraries, install them by running the following commands from cmd.exe or your shell.
pip install dask==2.14.0
pip install toolz
pip install fsspec==0.3.1
Download hurricane data from NCEI FTP portal¶
The National Centers for Environmental Information, formerly National Climatic Data Center shares the historic hurricane track datasets at ftp://eclipse.ncdc.noaa.gov/pub/ibtracs/v03r09/all/csv/. We use the ftplib
Python library to login in and download these datasets.
# imports for downloading data from FTP site
import os
from ftplib import FTP
# imports to process data using DASK
from dask import delayed
import dask.dataframe as ddf
# imports for data analysis and visualization
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
# imports to perform spatial aggregation using ArcGIS GeoAnalytics server
from arcgis.gis import GIS
from arcgis.geoanalytics import get_datastores
from arcgis.geoanalytics.summarize_data import reconstruct_tracks
import arcgis
# miscellaneous imports
from pprint import pprint
from copy import deepcopy
Establish an anonymous connection to FTP site.
conn = FTP(host='eclipse.ncdc.noaa.gov')
conn.login()
Change directory to folder containing the hurricane files. List the files.
conn.cwd('/pub/ibtracs/v03r10/all/csv/year/')
file_list = conn.nlst()
len(file_list)
Print the top 10 items.
file_list[:10]
Download each file into the hurricanes_raw
directory¶
data_dir = r'data/hurricanes_data/'
if 'hurricanes_raw' not in os.listdir(data_dir):
os.mkdir(os.path.join(data_dir,'hurricanes_raw'))
hurricane_raw_dir = os.path.join(data_dir,'hurricanes_raw')
os.listdir(data_dir)
Now we are going to download data from 1842-2017, whih might take around 15 mins.
file_path = hurricane_raw_dir
for file in file_list:
with open(os.path.join(file_path, file), 'wb') as file_handle:
try:
conn.retrbinary('RETR ' + file, file_handle.write, 1024)
print(f'Downloaded {file}')
except Exception as download_ex:
print(f'Error downloading {file} + {str(download_ex)}')
Process CSV files by removing header rows¶
The CSV files have multiple header rows. Let us start by processing one of the files as an example.
csv_path = os.path.join(hurricane_raw_dir,'Year.2017.ibtracs_all.v03r10.csv')
df = pd.read_csv(csv_path)
df.head()
The input looks mangled. This is because the file's row 1
has a header that pandas fails to read. So let us skip that row.
df = pd.read_csv(csv_path, skiprows=1)
df.head()
A little better. But the file's 3rd row is also a header. Let us drop that row.
df.drop(labels=0, axis=0, inplace=True)
df.head()
Automate across all files¶
Now we need to repeat the above cleaning steps across all CSV files. In the steps below, we will read all CSV files, drop the headers, and write to disk. This step is necessary as it will ease subsequent processing using the DASK library.
file_path = hurricane_raw_dir
num_records = {}
for file in file_list:
df = pd.read_csv(os.path.join(file_path, file), skiprows=1)
num_records[str(file.split('.')[1])] = df.shape[0]
df.drop(labels=0, axis=0, inplace=True)
df.to_csv(os.path.join(file_path, file))
print(f'Processed {file}')
Cleaning hurricane observations with Dask¶
The data collected from NOAA NCDC source is just too large to clean with Pandas or Excel. With 350,000 x 200
in dense matrix, this data is larger than memory for a normal computer. Hence traditional packages such as Pandas cannot be used as they expect data to fit fully in memory.
Thus, in this part of the study, we use Dask, a distributed data analysis library. Functionally, Dask provides a DataFrame
object that behaves similar to a traditional pandas DataFrame
object. You can perform slicing, dicing, exploration on them. However transformative operations on the DataFrame
get queued and are operated only when necessary. When executed, Dask will read data in chunks, distribute it to workers (be it cores on a single machine or multiple machines in a cluster set up) and collect the data back for you. Thus, DASK allows you to work with any larger than memory dataset as it performs operations on chunks of it, in a distributed manner.
Read input CSV data¶
As mentioned earlier, DASK allows you to work with larger than memory datasets. These datasets can reside as one large file or as multiple files in a folder. For the latter, DASK allows you to just specify the folder containing the datasets as input. In turn, it provides you a single DataFrame
object that represents all your datasets combined together. The operations you perform on this DataFrame
get queued and executed only when necessary.
fld_path = hurricane_raw_dir
csv_path = os.path.join(fld_path,'*.csv')
Preemptively, specify the assortment of values that should be treated as null values.
table_na_values=['-999.','-999','-999.000', '-1', '-1.0','0','0.0']
full_df = ddf.read_csv(csv_path, na_values=table_na_values, dtype={'Center': 'object'})
You can query the top few (or bottom few) records as you do on a regular Pandas DataFrame
object.
full_df.head()
Drop the first duplicate index column.
full_df = full_df.drop(labels=['Unnamed: 0'], axis=1)
all_columns=list(full_df.columns)
len(all_columns)
This dataset has 200
columns. Not all are unique, as you can see from the print out below:
pprint(all_columns, compact=True, width=100)
Reading the metadata from NOAA NCDC site, we find sensor measurements get unique columns if they are collected by a different agency. Thus we find multiple pressure, wind speed, latitude, longitude, etc. columns with different suffixes and prefixes. Data is sparse as it gets distributed between these columns. For our geospatial analysis, it suffices if we can merge these columns together and get location information from the coordinates.
Merge all location columns¶
Below we prototype merging location columns. If this succeeds, we will proceed to merge all remaining columns.
lat_columns = [x for x in all_columns if 'lat' in x.lower()]
lon_columns = [x for x in all_columns if 'lon' in x.lower()]
for x in zip(lat_columns, lon_columns):
print(x)
In this dataset, if data is collected by 1 agency, the corresponding duplicate columns from other agencies are empty. However there may be exceptions. Hence we define a custom function that will pick median value for a row, from a given list of columns. This way, we can consolidate latitude / longitude information from all the agencies.
def pick_median_value(row, col_list):
return row[col_list].median()
full_df['latitude_merged'] = full_df.apply(pick_median_value, axis=1,
col_list = lat_columns)
full_df['longitude_merged'] = full_df.apply(pick_median_value, axis=1,
col_list = lon_columns)
With dask
, the above operation was delayed and stored in a queue. It has not been evaluated yet. Next, let us evaluate for 5
records and print output. If results look good, we will merge all remaining related columns together.
full_df.head(5)
The results look good. Two additional columns (latitude_merged
, longitude_merged
) have been added. By merging related columns, the redundant sparse columns can be removed, thereby simplifying the dimension of the input dataset.
Now that this prototype looks good, we will proceed by identifying the lists of remaining columns that are redundant and can be merged.
Merge similar columns¶
To keep track of which columns have been accounted for, we will duplicate the all_columns
list and remove ones that we have identified.
columns_tracker = deepcopy(all_columns)
len(columns_tracker)
From the columns_tracker
list, let us remove the redundant columns we already identified for location columns.
columns_tracker = [x for x in columns_tracker if x not in lat_columns]
columns_tracker = [x for x in columns_tracker if x not in lon_columns]
len(columns_tracker)
Thus, we have reduced the number of columns from 200
to 142
. We will progressively reduce this while retaining key information.
Merge wind columns¶
Wind, pressure, grade are some of the meteorological observations this dataset contains. To start off, let us identify the wind columns:
# pick all columns that have 'wind' in name
wind_columns = [x for x in columns_tracker if 'wind' in x.lower()]
# based on metadata doc, we decide to eliminate percentile and wind distance columns
columns_to_eliminate = [x for x in wind_columns if 'radii' in x or 'percentile' in x.lower()]
# trim wind_columns by removing the ones we need to eliminate
wind_columns = [x for x in wind_columns if x not in columns_to_eliminate]
wind_columns
full_df['wind_merged'] = full_df.apply(pick_median_value, axis=1,
col_list = wind_columns)
Merge pressure columns¶
We proceed to identify all pressure
columns. But before that, we update the columns_tracker
list by removing those we identified for wind:
columns_tracker = [x for x in columns_tracker if x not in wind_columns]
columns_tracker = [x for x in columns_tracker if x not in columns_to_eliminate]
len(columns_tracker)
# pick all columns that have 'pres' in name
pressure_columns = [x for x in columns_tracker if 'pres' in x.lower()]
# from metadata, we eliminate percentile and pres distance columns
if columns_to_eliminate:
columns_to_eliminate.extend([x for x in pressure_columns if 'radii' in x or 'percentile' in x.lower()])
else:
columns_to_eliminate = [x for x in pressure_columns if 'radii' in x or 'percentile' in x.lower()]
# trim wind_columns by removing the ones we need to eliminate
pressure_columns = [x for x in pressure_columns if x not in columns_to_eliminate]
pressure_columns
full_df['pressure_merged'] = full_df.apply(pick_median_value, axis=1,
col_list = pressure_columns)
Merge grade columns¶
columns_tracker = [x for x in columns_tracker if x not in pressure_columns]
columns_tracker = [x for x in columns_tracker if x not in columns_to_eliminate]
len(columns_tracker)
Notice the length of columns_tracker
is reducing progressively as we identify redundant columns.
# pick all columns that have 'grade' in name
grade_columns = [x for x in columns_tracker if 'grade' in x.lower()]
grade_columns
full_df['grade_merged'] = full_df.apply(pick_median_value, axis=1,
col_list = grade_columns)
Merge eye diameter columns¶
columns_tracker = [x for x in columns_tracker if x not in grade_columns]
len(columns_tracker)
# pick all columns that have 'eye' in name
eye_dia_columns = [x for x in columns_tracker if 'eye' in x.lower()]
eye_dia_columns
full_df['eye_dia_merged'] = full_df.apply(pick_median_value, axis=1,
col_list = eye_dia_columns)
Identify remaining redundant columns¶
columns_tracker = [x for x in columns_tracker if x not in eye_dia_columns]
len(columns_tracker)
We are down to 49
columns, let us visualize what those look like.
pprint(columns_tracker, width=119, compact=True)
Based on metadata shared by data provider, we choose to retain only the first 11
columns. We add the rest to the list columns_to_eliminate
.
columns_to_eliminate.extend(columns_tracker[11:])
pprint(columns_to_eliminate, width=119, compact=True)
Drop all redundant columns¶
So far, we have merged similar columns together and collected the lists of redundant columns to drop. Below we compile them into a single list.
len(full_df.columns)
columns_to_drop = lat_columns + lon_columns + wind_columns + pressure_columns + \
grade_columns + eye_dia_columns+columns_to_eliminate
len(columns_to_drop)
Perform delayed computation¶
In Dask, all computations are delayed and queued. The apply()
functions called earlier are not executed yet, however respective columns have been created as you can see from the DataFrame display above. In the cells below, we will call save()
to make Dask compute on this larger than memory dataset.
Calling visualize()
on the delayed compute operation or the DataFrame
object will plot the dask task queue as shown below. The graphic below provides a glimpse on how Dask distributes its tasks and how it reads this 'larger than memory dataset' in chunks and operates on them.
Drawing dask graphs requires the graphviz
python library and the graphviz
system library to be installed.
!conda install --yes -c anaconda graphviz
!conda install --yes -c conda-forge python-graphviz
full_df.visualize()