{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "remove_input" ] }, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "path_data = '../../../../data/'\n", "import matplotlib\n", "\n", "%matplotlib inline\n", "import matplotlib.pyplot as plt\n", "plt.style.use('fivethirtyeight')\n", "\n", "import warnings\n", "warnings.filterwarnings('ignore')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Classifying by One Variable ###\n", "\n", "Data scientists often need to classify individuals into groups according to shared features, and then identify some characteristics of the groups. For example, in the example using Galton's data on heights, we saw that it was useful to classify families according to the parents' midparent heights, and then find the average height of the children in each group.\n", "\n", "This section is about classifying individuals into categories that are not numerical. We begin by recalling the basic use of `group`. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Counting the Number in Each Category ###\n", "The `group` method with a single argument counts the number of rows for each category in a column. The result contains one row per unique value in the grouped column.\n", "\n", "Here is a small table of data on ice cream cones. The `group` method can be used to list the distinct flavors and provide the counts of each flavor." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cones = pd.DataFrame({\n", " 'Flavor':np.array(['strawberry', 'chocolate', 'chocolate', 'strawberry', 'chocolate']),\n", " 'Price':np.array([3.55, 4.75, 6.55, 5.25, 5.25])}\n", ")\n", "cones" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_grouped = cones.groupby([\"Flavor\"]).agg(\n", " count=pd.NamedAgg(column=\"Flavor\", aggfunc=\"count\")\n", ")\n", "\n", "df_grouped" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are two distinct categories, chocolate and strawberry. When we call `groupby` we must state what we want to do with the group data e.g. `count()`. Applying the `count()` method will create a column of counts whcih takes the names of the first column in the df by default, and contains the number of rows in each category. To make this easier to read we could change the count column to 'count'.\n", "\n", "Notice that this can all be worked out from just the `Flavor` column. Only the `Price` column name has been used, the data has not been used.\n", "\n", "But what if we wanted the total price of the cones of each different flavor? In this case we can apply a different method e.g. `sum()`, to `groupby`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Finding a Characteristic of Each Category ###\n", "The optional second argument of `group` names the function that will be used to aggregate values in other columns for all of those rows. For instance, `sum` will sum up the prices in all rows that match each category. This result also contains one row per unique value in the grouped column, but it has the same number of columns as the original table.\n", "\n", "To find the total price of each flavor, we call `group` again, with `Flavor` as its first argument as before. But this time there is a second argument: the function name `sum`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_grouped_by_price = cones.groupby([\"Flavor\"]).agg(\n", " Price_sum=pd.NamedAgg(column=\"Price\", aggfunc=\"sum\")\n", ")\n", "\n", "df_grouped_by_price" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To create this new table, `groupby` has calculated the **sum** of the `Price` entries in all the rows corresponding to each distinct flavor. The prices in the three `chocolate` rows add up to 16.55 (in whatever currency). The prices in the two `strawberry` rows have a total of 8.80.\n", "\n", "Using pandas `groupby aggregation` we can compute a summary statistic (or statistics). The label of the newly created column is `Price sum`, which is created by taking the label of the column being summed, and appending the word `sum` in the *aggregation pipeline*. \n", "\n", "In this insatnce there are only two columns so when `group` finds the `sum` of all columns other than the one with the categories, there is no need to specify that it has to `sum` the prices. Using the [`Pandas NamedAgg`](https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#aggregation) function we can name the column contining the results of the aggregation.\n", "\n", "To see in more detail what `group` is doing, notice that you could have figured out the total prices yourself, not only by mental arithmetic but also using code. For example, to find the total price of all the chocolate cones, you could start by creating a new table consisting of only the chocolate cones, and then accessing the column of prices:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cones[cones['Flavor'] == 'chocolate']['Price']" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cones[cones['Flavor'] == 'chocolate'][['Price']]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.sum(cones[cones['Flavor'] == 'chocolate'][['Price']])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.sum([cones[cones['Flavor'] == 'chocolate'][['Price']]])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is what `groupby` is doing for each distinct value in `Flavor`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# For each distinct value in `Flavor, access all the rows\n", "# and create an array of `Price`\n", "\n", "cones_choc = cones[cones['Flavor'] == 'chocolate']['Price']\n", "\n", "cones_strawb = cones[cones['Flavor'] =='strawberry']['Price']\n", "\n", "# Display the arrays in a table\n", "\n", "cones_choc = np.array(cones_choc)\n", "cones_strawb = np.array(cones_strawb)\n", "\n", "grouped_cones = pd.DataFrame({\n", " 'Flavor':np.array(['chocolate', 'strawberry']),\n", " 'Array of All the Prices':[cones_choc, cones_strawb]}\n", ")\n", "\n", "#priceTotals\n", "\n", "# Append a column with the sum of the `Price` values in each array\n", "\n", "price_totals = grouped_cones\n", "\n", "price_totals['Sum of the Array'] = np.array([sum(cones_choc), sum(cones_strawb)])\n", "\n", "price_totals" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can replace `sum` by any other functions that work on arrays. For example, you could use `max` to find the largest price in each category:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cones.groupby('Flavor').max()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### *Or* ###" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "price_max = cones.groupby([\"Flavor\"]).agg(\n", " Price_Max=pd.NamedAgg(column=\"Price\", aggfunc=\"max\")\n", ")\n", "\n", "price_max" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once again, `groupby` creates arrays of the prices in each `Flavor` category. But now it finds the `max` of each array:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "price_max = grouped_cones.copy()\n", "\n", "price_max['Max of the Array'] = np.array([max(cones_choc), max(cones_strawb)])\n", "\n", "price_max" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Indeed, the original call to `group` with just one argument has the same effect as using `len` as the function and then cleaning up the table." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "array_length = grouped_cones.copy()\n", "\n", "array_length['Length of the Array'] = np.array([len(cones_choc), len(cones_strawb)])\n", "\n", "array_length" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example: NBA Salaries ###\n", "The table `nba` contains data on the 2015-2016 players in the National Basketball Association. We have examined these data earlier. Recall that salaries are measured in millions of dollars." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nba1 = pd.read_csv(path_data + 'nba_salaries.csv')\n", "\n", "nba = nba1.rename(columns={\"'15-'16 SALARY\": 'SALARY'})\n", "\n", "nba" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**1.** How much money did each team pay for its players' salaries?\n", "\n", "The only columns involved are `TEAM` and `SALARY`. We have to `group` the rows by `TEAM` and then `sum` the salaries of the groups. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "teams_and_money = nba[['TEAM', 'SALARY']]\n", "\n", "teams_and_money.groupby('TEAM').sum()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**2.** How many NBA players were there in each of the five positions?\n", "\n", "We have to classify by `POSITION`, and count. This can be achieved by applying the `count()` method to a `groupby` or and the aggregation method with `aggfunc=\"count\"`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#nba.groupby('POSITION').count()\n", "\n", "# -- or\n", "\n", "position_count = nba.groupby([\"POSITION\"]).agg(\n", " count=pd.NamedAgg(column=\"PLAYER\", aggfunc=\"count\")\n", ")\n", "\n", "position_count" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**3.** What was the average salary of the players at each of the five positions?\n", "\n", "This time, we have to group by `POSITION` and take the mean of the salaries. For clarity, we will work with a table of just the positions and the salaries." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "positions_and_money = nba[['POSITION', 'SALARY']]\n", "\n", "positions_and_money.groupby('POSITION').mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Center was the most highly paid position, at an average of over 6 million dollars.\n", "\n", "If we had not selected the two columns as our first step, `group` would not attempt to \"average\" the categorical columns in `nba`. (It is impossible to average two strings like \"Atlanta Hawks\" and \"Boston Celtics\".) It performs arithmetic only on numerical columns and leaves the rest blank." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nba_mean = nba.groupby('POSITION').mean()\n", "\n", "nba_mean\n", "\n", "nba_mean = nba.groupby([\"POSITION\"]).agg(\n", " SALARY_mean=pd.NamedAgg(column=\"SALARY\", aggfunc=\"mean\")\n", ")\n", "\n", "nba_mean" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.8.5" } }, "nbformat": 4, "nbformat_minor": 1 }