Sometimes numerical values make more sense if clustered together. For example, if we’re trying to model traffic (#cars on road) with time of the day (minutes). The exact minute of an hour might not be that relevant for predicting traffic as compared to actual period of the day like “Morning”, “Afternoon”, “Evening”, “Night”, “Late Night”. Modeling traffic this way will be more intuitive and will avoid overfitting.
Here we define a simple function which can be re-used for binning any variable fairly easily.
#Binning:defbinning(col,cut_points,labels=None):#Define min and max values: minval = col.min() maxval = col.max()#create list by adding min and max to cut_points break_points = [minval] + cut_points + [maxval]#if no labels provided, use default labels 0 ... (n-1)ifnot labels: labels =range(len(cut_points)+1)#Binning using cut function of pandas colBin = pd.cut(col,bins=break_points,labels=labels,include_lowest=True)return colBin#Binning age:cut_points = [90,140,190]labels = ["low","medium","high","very high"]data["LoanAmount_Bin"]=binning(data["LoanAmount"], cut_points, labels)print (pd.value_counts(data["LoanAmount_Bin"], sort=False))
Coding nominal data using Pandas
Often, we find a case where we’ve to modify the categories of a nominal variable. This can be due to various reasons:
Some algorithms (like Logistic Regression) require all inputs to be numeric. So nominal variables are mostly coded as 0, 1….(n-1) Sometimes a category might be represented in 2 ways. For e.g. temperature might be recorded as “High”, “Medium”, “Low”, “H”, “low”. Here, both “High” and “H” refer to same category. Similarly, in “Low” and “low” there is only a difference of case. But, python would read them as different levels. Some categories might have very low frequencies and its generally a good idea to combine them. Here I’ve defined a generic function which takes in input as a dictionary and codes the values using ‘replace’ function in Pandas.
#Define a generic function using Pandas replace functiondefcoding(col,codeDict): colCoded = pd.Series(col, copy=True)for key, value in codeDict.items(): colCoded.replace(key, value, inplace=True)return colCoded#Coding LoanStatus as Y=1, N=0:print'Before Coding:'print pd.value_counts(data["Loan_Status"])data["Loan_Status_Coded"]=coding(data["Loan_Status"], {'N':0,'Y':1})print'\nAfter Coding:'print pd.value_counts(data["Loan_Status_Coded"])
plt.figure(figsize=(15, 5))sns.scatterplot(data=df, x='Year', y='Country', size='Exports', sizes=(20, 200), hue='Exports');plt.title('Exports by Country and Year')plt.show()