<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Ejercicio Llamadas al 911 - Solucion
Para este ejercicio vamos analizar la informacion referente a las llamadas al 911 Kaggle. La informacion contiene los siguientes campos
Step1:  Import visualization libraries and set %matplotlib inline.
Step2:  Read in the csv file as a dataframe called df
Step3:  Check the info() of the df
Step4:  Check the head of df
Step5:  Basic Questions
 What are the top 5 zipcodes for 911 calls?
Step6:  What are the top 5 townships (twp) for 911 calls?
Step7:  Take a look at the 'title' column, how many unique title codes are there?
Step8:  Creating new features
 In the titles column there are "Reasons/Departments" specified before the title code. These are EMS, Fire, and Traffic. Use .apply() with a custom lambda expression to create a new column called "Reason" that contains this string value. 
For example, if the title column value is EMS
Step9:  What is the most common Reason for a 911 call based off of this new column?
Step10:  Now use seaborn to create a countplot of 911 calls by Reason.
Step11:  Now let us begin to focus on time information. What is the data type of the objects in the timeStamp column?
Step12:  You should have seen that these timestamps are still strings. Use pd.to_datetime to convert the column from strings to DateTime objects.
Step13:  You can now grab specific attributes from a Datetime object by calling them. For example
Step14:  Notice how the Day of Week is an integer 0-6. Use the .map() with this dictionary to map the actual string names to the day of the week
Step15:  Now use seaborn to create a countplot of the Day of Week column with the hue based off of the Reason column.
Step16:  Now do the same for Month
Step17:  Did you notice something strange about the Plot?
Step18:  You should have noticed it was missing some Months, let's see if we can maybe fill in this information by plotting the information in another way, possibly a simple line plot that fills in the missing months, in order to do this, we'll need to do some work with pandas...
 Now create a gropuby object called byMonth, where you group the DataFrame by the month column and use the count() method for aggregation. Use the head() method on this returned DataFrame.
Step19:  Now create a simple plot off of the dataframe indicating the count of calls per month.
Step20:  Now see if you can use seaborn's lmplot() to create a linear fit on the number of calls per month. Keep in mind you may need to reset the index to a column.
Step21:  Create a new column called 'Date' that contains the date from the timeStamp column. You'll need to use apply along with the .date() method.
Step22:  Now groupby this Date column with the count() aggregate and create a plot of counts of 911 calls.
Step23:  Now recreate this plot but create 3 separate plots with each plot representing a Reason for the 911 call
Step24:  Now let's move on to creating  heatmaps with seaborn and our data. We'll first need to restructure the dataframe so that the columns become the Hours and the Index becomes the Day of the Week. There are lots of ways to do this, but I would recommend trying to combine groupby with an unstack method. Reference the solutions if you get stuck on this!
Step25:  Now create a HeatMap using this new DataFrame.
Step26:  Now create a clustermap using this DataFrame.
Step27:  Now repeat these same plots and operations, for a DataFrame that shows the Month as the column.
<ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
Explanation: Ejercicio Llamadas al 911 - Solucion
Para este ejercicio vamos analizar la informacion referente a las llamadas al 911 Kaggle. La informacion contiene los siguientes campos:
lat : String variable, Latitud
lng: String variable, Longitud
desc: String variable, Descripcion del tipo de emergencia
zip: String variable, Codigo postal
title: String variable, Titulo
timeStamp: String variable, YYYY-MM-DD HH:MM:SS
twp: String variable, Municipio
addr: String variable, Direccion
e: String variable, Variable dummy (siempre 1)
Data and Setup
 Import numpy and pandas
End of explanation
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
%matplotlib inline
Explanation: Import visualization libraries and set %matplotlib inline.
End of explanation
df = pd.read_csv('911.csv')
Explanation: Read in the csv file as a dataframe called df
End of explanation
df.info()
Explanation: Check the info() of the df
End of explanation
df.head(3)
Explanation: Check the head of df
End of explanation
df['zip'].value_counts().head(5)
Explanation: Basic Questions
 What are the top 5 zipcodes for 911 calls?
End of explanation
df['twp'].value_counts().head(5)
Explanation: What are the top 5 townships (twp) for 911 calls?
End of explanation
df['title'].nunique()
Explanation: Take a look at the 'title' column, how many unique title codes are there?
End of explanation
df['Reason'] = df['title'].apply(lambda title: title.split(':')[0])
Explanation: Creating new features
 In the titles column there are "Reasons/Departments" specified before the title code. These are EMS, Fire, and Traffic. Use .apply() with a custom lambda expression to create a new column called "Reason" that contains this string value. 
For example, if the title column value is EMS: BACK PAINS/INJURY , the Reason column value would be EMS.
End of explanation
df['Reason'].value_counts()
Explanation: What is the most common Reason for a 911 call based off of this new column?
End of explanation
sns.countplot(x='Reason',data=df,palette='viridis')
Explanation: Now use seaborn to create a countplot of 911 calls by Reason.
End of explanation
type(df['timeStamp'].iloc[0])
Explanation: Now let us begin to focus on time information. What is the data type of the objects in the timeStamp column?
End of explanation
df['timeStamp'] = pd.to_datetime(df['timeStamp'])
Explanation: You should have seen that these timestamps are still strings. Use pd.to_datetime to convert the column from strings to DateTime objects.
End of explanation
df['Hour'] = df['timeStamp'].apply(lambda time: time.hour)
df['Month'] = df['timeStamp'].apply(lambda time: time.month)
df['Day of Week'] = df['timeStamp'].apply(lambda time: time.dayofweek)
Explanation: You can now grab specific attributes from a Datetime object by calling them. For example:
time = df['timeStamp'].iloc[0]
time.hour
You can use Jupyter's tab method to explore the various attributes you can call. Now that the timestamp column are actually DateTime objects, use .apply() to create 3 new columns called Hour, Month, and Day of Week. You will create these columns based off of the timeStamp column, reference the solutions if you get stuck on this step.
End of explanation
dmap = {0:'Mon',1:'Tue',2:'Wed',3:'Thu',4:'Fri',5:'Sat',6:'Sun'}
df['Day of Week'] = df['Day of Week'].map(dmap)
Explanation: Notice how the Day of Week is an integer 0-6. Use the .map() with this dictionary to map the actual string names to the day of the week: 
dmap = {0:'Mon',1:'Tue',2:'Wed',3:'Thu',4:'Fri',5:'Sat',6:'Sun'}
End of explanation
sns.countplot(x='Day of Week',data=df,hue='Reason',palette='viridis')
# To relocate the legend
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
Explanation: Now use seaborn to create a countplot of the Day of Week column with the hue based off of the Reason column.
End of explanation
sns.countplot(x='Month',data=df,hue='Reason',palette='viridis')
# To relocate the legend
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
Explanation: Now do the same for Month:
End of explanation
# It is missing some months! 9,10, and 11 are not there.
Explanation: Did you notice something strange about the Plot?
End of explanation
byMonth = df.groupby('Month').count()
byMonth.head()
Explanation: You should have noticed it was missing some Months, let's see if we can maybe fill in this information by plotting the information in another way, possibly a simple line plot that fills in the missing months, in order to do this, we'll need to do some work with pandas...
 Now create a gropuby object called byMonth, where you group the DataFrame by the month column and use the count() method for aggregation. Use the head() method on this returned DataFrame.
End of explanation
# Could be any column
byMonth['twp'].plot()
Explanation: Now create a simple plot off of the dataframe indicating the count of calls per month.
End of explanation
sns.lmplot(x='Month',y='twp',data=byMonth.reset_index())
Explanation: Now see if you can use seaborn's lmplot() to create a linear fit on the number of calls per month. Keep in mind you may need to reset the index to a column.
End of explanation
df['Date']=df['timeStamp'].apply(lambda t: t.date())
Explanation: Create a new column called 'Date' that contains the date from the timeStamp column. You'll need to use apply along with the .date() method.
End of explanation
df.groupby('Date').count()['twp'].plot()
plt.tight_layout()
Explanation: Now groupby this Date column with the count() aggregate and create a plot of counts of 911 calls.
End of explanation
df[df['Reason']=='Traffic'].groupby('Date').count()['twp'].plot()
plt.title('Traffic')
plt.tight_layout()
df[df['Reason']=='Fire'].groupby('Date').count()['twp'].plot()
plt.title('Fire')
plt.tight_layout()
df[df['Reason']=='EMS'].groupby('Date').count()['twp'].plot()
plt.title('EMS')
plt.tight_layout()
Explanation: Now recreate this plot but create 3 separate plots with each plot representing a Reason for the 911 call
End of explanation
dayHour = df.groupby(by=['Day of Week','Hour']).count()['Reason'].unstack()
dayHour.head()
Explanation: Now let's move on to creating  heatmaps with seaborn and our data. We'll first need to restructure the dataframe so that the columns become the Hours and the Index becomes the Day of the Week. There are lots of ways to do this, but I would recommend trying to combine groupby with an unstack method. Reference the solutions if you get stuck on this!
End of explanation
plt.figure(figsize=(12,6))
sns.heatmap(dayHour,cmap='viridis')
Explanation: Now create a HeatMap using this new DataFrame.
End of explanation
sns.clustermap(dayHour,cmap='viridis')
Explanation: Now create a clustermap using this DataFrame.
End of explanation
dayMonth = df.groupby(by=['Day of Week','Month']).count()['Reason'].unstack()
dayMonth.head()
plt.figure(figsize=(12,6))
sns.heatmap(dayMonth,cmap='viridis')
sns.clustermap(dayMonth,cmap='viridis')
Explanation: Now repeat these same plots and operations, for a DataFrame that shows the Month as the column.
End of explanation
<END_TASK>