{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "l9hHDMhFjshW",
    "tags": []
   },
   "source": [
    "# Exploratory data analysis\n",
    "\n",
    "Data source: https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data\n",
    "\n",
    "Important attributes description:\n",
    "* SalePrice: The property's sale price in dollars. This is the target variable that you're trying to predict.\n",
    "* MSSubClass: The building class\n",
    "* BldgType: Type of dwelling\n",
    "* HouseStyle: Style of dwelling\n",
    "* OverallQual: Overall material and finish quality\n",
    "* OverallCond: Overall condition rating\n",
    "* YearBuilt: Original construction date\n",
    "* Heating: Type of heating\n",
    "* CentralAir: Central air conditioning\n",
    "* GrLivArea: Above grade (ground) living area square feet\n",
    "* BedroomAbvGr: Number of bedrooms above basement level"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Import used packages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "FVFwXLhL75FZ"
   },
   "outputs": [],
   "source": [
    "import pandas as pd # dataframes\n",
    "import numpy as np # matrices and linear algebra\n",
    "import matplotlib.pyplot as plt # plotting\n",
    "import seaborn as sns # another matplotlib interface - styled and easier to use"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load the data into the Pandas DataFrame - in our case it is a csv file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv('zsu_cv1_data.csv', sep=',')\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Pairplot\n",
    "- Plot pairwise relationships in a dataset\n",
    "- Scatterplots for multiple pairs of numerical attributes, see [this](https://seaborn.pydata.org/generated/seaborn.pairplot.html)\n",
    "- Select only numerical attributes from dataframe - *select_dtypes*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### If the dataset has too many columns, it is good to set pandas parameter *display.max_columns* to None so there is no such limit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with pd.option_context('display.max_columns', None):\n",
    "  display(df.select_dtypes(include=np.number))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Select only an interesting features for paiplot visualization\n",
    "- The pairplot might be too big to see anything in the visualization"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "selected_columns = ['LotFrontage', 'LotArea', 'OverallQual', 'OverallCond', 'YearBuilt', 'GrLivArea', 'GarageYrBlt', 'GarageArea', 'SalePrice']\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Notice that both OverallQual and OverallCond columns are rather categorical features even though they are represented by numerical values thus one would expect that the features are numerical but they aren't so scatter plot may not be the best way to visualize this type of data\n",
    "\n",
    "- Let's select only appropropriate features this time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "selected_columns = ['LotFrontage', 'LotArea', 'YearBuilt', 'GrLivArea', 'GarageYrBlt', 'GarageArea', 'SalePrice']\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## In following steps we want to threat OverallQual and OverallCond as categories instead of numbers\n",
    "- for modifying of column's types you can use function *astype*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Are you able to say which categorical attributes effect the price right now?\n",
    "- Yeah... me neither so let's find out by plotting the data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Start with selection of only the categorical features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Now we need to [melt](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html) the dataset into the standard data format"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = pd.melt(df, id_vars=['SalePrice'], value_vars=qualitative_columns)\n",
    "f.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### And finally we can use the [FacetGrid](https://seaborn.pydata.org/generated/seaborn.FacetGrid.html) to crate a grid of subplots and map boxplot to every cell"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def boxplot(x, y, **kwargs):\n",
    "    sns.boxplot(x=x, y=y)\n",
    "    x=plt.xticks(rotation=90)\n",
    "\n",
    "g = sns.FacetGrid(f, col=\"variable\",  col_wrap=2, sharex=False, sharey=False, height=5)\n",
    "g = g.map(boxplot, \"value\", \"SalePrice\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Another very useful feature is the [subplots](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html) function for defining our own grids\n",
    "### We will plot boxplots together with the individual value counts using barplot for every categorical feature"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(len(qualitative_columns), 2, figsize=(10, 150))\n",
    "\n",
    "for i, col in enumerate(qualitative_columns):\n",
    "    ax_left = fig.axes[2*i]\n",
    "    ax_right = fig.axes[2*i + 1]\n",
    "    sns.boxplot(data=df, x=col, y='SalePrice', ax=ax_left)\n",
    "    ax_left.set_xticklabels(ax_left.xaxis.get_majorticklabels(), rotation=60)\n",
    "    sns.countplot(data=df, x=col, ax=ax_right)\n",
    "    ax_right.set_xticklabels(ax_right.xaxis.get_majorticklabels(), rotation=60)\n",
    "        \n",
    "fig.tight_layout()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Categorical heatmap\n",
    "\n",
    "- We have selected some interesting categorical columns\n",
    "\n",
    "**Neighborhood: Physical locations within Ames city limits**\n",
    "\n",
    "       Blmngtn\tBloomington Heights\n",
    "       Blueste\tBluestem\n",
    "       BrDale\tBriardale\n",
    "       BrkSide\tBrookside\n",
    "       ClearCr\tClear Creek\n",
    "       CollgCr\tCollege Creek\n",
    "       Crawfor\tCrawford\n",
    "       Edwards\tEdwards\n",
    "       Gilbert\tGilbert\n",
    "       IDOTRR\tIowa DOT and Rail Road\n",
    "       MeadowV\tMeadow Village\n",
    "       Mitchel\tMitchell\n",
    "       Names\tNorth Ames\n",
    "       NoRidge\tNorthridge\n",
    "       NPkVill\tNorthpark Villa\n",
    "       NridgHt\tNorthridge Heights\n",
    "       NWAmes\tNorthwest Ames\n",
    "       OldTown\tOld Town\n",
    "       SWISU\tSouth & West of Iowa State University\n",
    "       Sawyer\tSawyer\n",
    "       SawyerW\tSawyer West\n",
    "       Somerst\tSomerset\n",
    "       StoneBr\tStone Brook\n",
    "       Timber\tTimberland\n",
    "       Veenker\tVeenker\n",
    "\n",
    "**HouseStyle: Style of dwelling**\n",
    "\n",
    "       1Story\tOne story\n",
    "       1.5Fin\tOne and one-half story: 2nd level finished\n",
    "       1.5Unf\tOne and one-half story: 2nd level unfinished\n",
    "       2Story\tTwo story\n",
    "       2.5Fin\tTwo and one-half story: 2nd level finished\n",
    "       2.5Unf\tTwo and one-half story: 2nd level unfinished\n",
    "       SFoyer\tSplit Foyer\n",
    "       SLvl\tSplit Level\n",
    "\n",
    "**BsmtFinType1: Rating of basement finished area**\n",
    "\n",
    "       GLQ\tGood Living Quarters\n",
    "       ALQ\tAverage Living Quarters\n",
    "       BLQ\tBelow Average Living Quarters\t\n",
    "       Rec\tAverage Rec Room\n",
    "       LwQ\tLow Quality\n",
    "       Unf\tUnfinshed\n",
    "       NA\tNo Basement\n",
    "\n",
    "### Let's vizualize a relationship between *HouseStyle* and *Neighborhood* using heatmap with counts of every combination of the two attributes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(12, 6))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Let's vizualize a relationship between *HouseStyle* and *BsmtFinType1* using heatmap. Counts is not the only option. In this case, calculate median price for *HouseStyle* and *BsmtFinType1* categories combinations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(12, 6))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Correlation\n",
    "- Take a look at [this link](https://www.dummies.com/education/math/statistics/how-to-interpret-a-correlation-coefficient-r/)\n",
    "- See also [this](https://www.simplypsychology.org/correlation.html) or [this](https://www.investopedia.com/ask/answers/032515/what-does-it-mean-if-correlation-coefficient-positive-negative-or-zero.asp) for some more info about the topic"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(12, 9))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Which color will be more appropropriate for corellation representation?\n",
    "- Change color map *cmap* (e.g. RdYlGn)\n",
    "- Set limits to adjust color map values from -1 to 1 (attributes *vmin*, *vmax*)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(12, 9))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## What can we say about the values in this correlation sub-matrix?\n",
    "- Let's focus only some subset of the features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "selected_columns = ['LotFrontage', 'LotArea', 'YearBuilt', 'GrLivArea', 'GarageYrBlt', 'GarageArea', 'SalePrice']\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(12, 9))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Add values to the heatmap and amplify heatmap's readability"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(12, 9))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# We highly recommend taking a look at the plot gallery for some inspiration!\n",
    "- https://seaborn.pydata.org/api.html"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Let's try for example scatter plot with regression line fron the example gallery\n",
    "- What insight does it give us about the trend?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(12, 12))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Task (2p)\n",
    "1. Create two filtered dataframes:\n",
    "- The first one will contain only the data for BldgType = '1Fam'\n",
    "- The other one will contain only the data for BldgType = 'Twnhs' or 'TwnhsE'\n",
    "\n",
    "2. Plot correlation matrices for both of the datasets for the features:\n",
    "- ['LotFrontage', 'LotArea', 'YearBuilt', 'GrLivArea', 'GarageYrBlt', 'GarageArea', 'SalePrice']\n",
    "\n",
    "3. Do you see any differences or similarities in the correlation matrices? Which features you take as correlated and which are not according to you?\n",
    "- Write down the insight obtained to the Markdown cell."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "ZSU_cv1_introduction_jupyter_pandas_visualization.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
