{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "remove_input" ] }, "outputs": [], "source": [ "path_data = '../../../data/'\n", "\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "plt.style.use('fivethirtyeight')\n", "%matplotlib inline\n", "\n", "import warnings\n", "warnings.filterwarnings('ignore')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Sampling and Empirical Distributions ###\n", "An important part of data science consists of making conclusions based on the data in random samples. In order to correctly interpret their results, data scientists have to first understand exactly what random samples are.\n", "\n", "In this chapter we will take a more careful look at sampling, with special attention to the properties of large random samples. \n", "\n", "Let's start by drawing some samples. Our examples are based on the top_movies.csv data set." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "top_raw = pd.read_csv(path_data + 'top_movies.csv')\n", "\n", "top1 = top_raw.copy()\n", "\n", "top1['Row Index'] = np.arange(len(top1))\n", "\n", "top1.head(5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Column Position ###\n", "Notice that column we have created 'Row Index' is positioned last in the df, to make life easier we would like this column to be first in the df. There are several ways in which we can move the position of this column e.g. we could [`pop`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pop.html) the column out of the df then re-insert it in the desired position or we could [`drop`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html) the column then re-insert into the df. Yet another method would be `insert` the column ['Row Index'](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.insert.html) at the desired df position.\n", "\n", "[Pandas 'pop'](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pop.html)\n", "\n", "[Pandas 'drop'](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html)\n", "\n", "[Pandas 'insert'](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.insert.html)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Insert ###" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "top2 = top1.drop(columns=['Row Index'])\n", "\n", "top2.insert(0, 'Row Index', np.arange(len(top2)))\n", "\n", "top2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Rename Index ###\n", "Rather than creating a new column we can rename the existing axis, howeverby doing this we must remember that 'Row Index' is the actual df index and not simple 'column'" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "top = top1.drop(columns=['Row Index'])\n", "\n", "top = top.rename_axis('Row Index', axis='columns')\n", "\n", "top" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Number Formatting ###\n", "Before going on to process the data we may wish to adjust the format of data (as we have previously). To achieve this we can employ Pandas 'Display Values' which allows us to `format` an entire df or to specific columns.\n", "\n", "[Pandas format](https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html#Finer-Control:-Display-Values)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "top.head(10).style.format({'Gross': \"{:,}\", 'Gross (Adjusted)': '{:,}'})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Sampling Rows of a Table ###\n", "Each row of a data table represents an individual; in `top`, each individual is a movie. Sampling individuals can thus be achieved by sampling the rows of a table.\n", "\n", "The contents of a row are the values of different variables measured on the same individual. So the contents of the sampled rows form samples of values of each of the variables." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Deterministic Samples ###\n", "\n", "When you simply specify which elements of a set you want to choose, without any chances involved, you create a ***deterministic*** *sample*.\n", "\n", "You have done this many times, for example by using [`df.iloc`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html) (**i**ndex **loc**ation and the df index values `[ ]`:\n", "\n", "[Pandas iloc](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "top.iloc[np.array([3, 18, 100])]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also use Pandas `contains` as a conditional operator:\n", "\n", "[Pandas where](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "top[top['Title'].str.contains('Harry Potter')]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "While these are samples, they are not random samples. They don't involve chance." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Probability Samples\n", "------------------" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For describing random samples, some terminology will be helpful.\n", "\n", "A *population* is the set of all elements from whom a sample will be drawn.\n", "\n", "A *probability sample* is one for which it is possible to calculate, before the sample is drawn, the chance with which any subset of elements will enter the sample.\n", "\n", "In a probability sample, all elements need not have the same chance of being chosen. \n", "\n", "### A Random Sampling Scheme ###\n", "\n", "For example, suppose you choose two people from a population that consists of three people A, B, and C, according to the following scheme:\n", "\n", "- Person A is chosen with probability 1.\n", "- One of Persons B or C is chosen according to the toss of a coin: if the coin lands heads, you choose B, and if it lands tails you choose C.\n", "\n", "This is a probability sample of size 2. Here are the chances of entry for all non-empty subsets:\n", "\n", " A: 1 \n", " B: 1/2\n", " C: 1/2\n", " AB: 1/2\n", " AC: 1/2\n", " BC: 0\n", " ABC: 0\n", "\n", "Person A has a higher chance of being selected than Persons B or C; indeed, Person A is certain to be selected. Since these differences are known and quantified, they can be taken into account when working with the sample. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### A Systematic Sample ###\n", "\n", "Imagine all the elements of the population listed in a sequence. One method of sampling starts by choosing a random position early in the list, and then evenly spaced positions after that. The sample consists of the elements in those positions. Such a sample is called a *systematic sample*. \n", "\n", "Here we will choose a systematic sample of the rows of `top`. We will start by picking one of the first 10 rows at random, and then we will pick applying the `take` method every 10th row after that. \n", "\n", "[Pandas take](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.take.html)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"\"\"Choose a random start among rows 0 through 9;\n", "then take every 10th row.\"\"\"\n", "\n", "start = np.random.choice(np.arange(10))\n", "top.take(np.arange(start, len(top), 10))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Run the cell a few times to see how the output varies. \n", "\n", "This systematic sample is a probability sample. In this scheme, all rows have chance $1/10$ of being chosen. For example, Row 23 is chosen if and only if Row 3 is chosen, and the chance of that is $1/10$. \n", "\n", "But not all subsets have the same chance of being chosen. Because the selected rows are evenly spaced, most subsets of rows have no chance of being chosen. The only subsets that are possible are those that consist of rows all separated by multiples of 10. Any of those subsets is selected with chance 1/10. Other subsets, like the subset containing the first 11 rows of the table, are selected with chance 0." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Random Samples Drawn With or Without Replacement ###\n", "In this course, we will mostly deal with the two most straightforward methods of sampling. \n", "\n", "The first is random sampling with replacement, which (as we have seen earlier) is the default behavior of `np.random.choice` when it samples from an array. \n", "\n", "The other, called a \"simple random sample\", is a sample drawn at random *without* replacement. Sampled individuals are not replaced in the population before the next individual is drawn. This is the kind of sampling that happens when you deal a hand from a deck of cards, for example. \n", "\n", "In this chapter, we will use simulation to study the behavior of large samples drawn at random with or without replacement. \n", "\n", "[Numpy random.choice](https://het.as.utexas.edu/HET/Software/Numpy/reference/generated/numpy.random.choice.html)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Drawing a random sample requires care and precision. It is not haphazard, even though that is a colloquial meaning of the word \"random\". If you stand at a street corner and take as your sample the first ten people who pass by, you might think you're sampling at random because you didn't choose who walked by. But it's not a random sample – it's a *sample of convenience*. You didn't know ahead of time the probability of each person entering the sample; perhaps you hadn't even specified exactly who was in the population." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "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 }