{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Intro to For loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```{note}\n", "For the first section of this page, the original content was developed by [Lisa Tagliaferri](https://twitter.com/lisaironcutter) for digitalocean.com released under the Creative Commons Attribution-NonCommercial-ShakeAlike 4.0 International Licence. The text of Lisa's tutorial had been modified in a minor way by [Todd Gureckis](http://gureckislab.org/~gureckis) in a few sections. Todd added 40 different examples of for loops ranging from simple to more complex. This page is released under the [license for this book](/LICENSE.html)\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using loops in computer programming allows us to automate and repeat similar tasks multiple times. This is very common in data analysis. In this tutorial, we’ll be covering Python’s **for loop**.\n", "\n", "A `for` loop implements the repeated execution of code based on a loop counter or loop variable. This means that `for` loops are used most often when the number of repetitions is known before entering the loop, unlike **while loops** which can run until some condition is met." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## For Loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In Python, `for` loops are constructed like so:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "for [iterating variable] in [sequence]:\n", " [do something]\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The something that is being done (known as a code block) will be executed until the sequence is over. The code block itself can consist of any number of lines of code, as long as they are tabbed over once from the left hand side of the code." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let’s look at a `for` loop that iterates through a range of values:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(0,5):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When we run this program, the output looks like this:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "for i in range(0,5):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This `for` loop sets up `i` as its iterating variable, and the sequence exists in the range of 0 to 5.\n", "\n", "Then within the loop we print out one integer per loop iteration. Keep in mind that in programming we tend to begin at index 0, so that is why although 5 numbers are printed out, they range from 0-4.\n", "\n", "You’ll commonly see and use `for` loops when a program needs to repeat a block of code a number of times." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## For Loops using range()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One of Python’s built-in immutable sequence types is `range()`. In loops, `range()` is used to control how many times the loop will be repeated.\n", "\n", "When working with `range()`, you can pass between 1 and 3 integer arguments to it:\n", "\n", "- `start` states the integer value at which the sequence begins, if this is not included then start begins at 0\n", "- `stop` is always required and is the integer that is counted up to but not included\n", "- `step` sets how much to increase (or decrease in the case of negative numbers) the next iteration, if this is omitted then step defaults to 1\n", "\n", "We’ll look at some examples of passing different arguments to `range()`.\n", "\n", "First, let’s only pass the `stop` argument, so that our sequence set up is `range(stop)`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(6):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the program above, the stop argument is 6, so the code will iterate from 0-6 (exclusive of 6):" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n" ] } ], "source": [ "for i in range(6):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, we’ll look at `range(start, stop)`, with values passed for when the iteration should start and for when it should stop:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(20,25):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, the range goes from 20 (inclusive) to 25 (exclusive), so the output looks like this:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "20\n", "21\n", "22\n", "23\n", "24\n" ] } ], "source": [ "for i in range(20,25):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The step argument of `range()` can be used to skip values within the sequence.\n", "\n", "With all three arguments, `step` comes in the final position: `range(start, stop, step)`. First, let’s use a `step` with a positive value:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(0,15,3):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this case, the `for` loop is set up so that the numbers from 0 to 15 print out, but at a step of 3, so that only every third number is printed, like so:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "3\n", "6\n", "9\n", "12\n" ] } ], "source": [ "for i in range(0,15,3):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also use a negative value for our `step` argument to iterate backwards, but we’ll have to adjust our start and stop arguments accordingly:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(100,0,-10):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, 100 is the `start` value, 0 is the `stop` value, and -10 is the range, so the loop begins at 100 and ends at 0, decreasing by 10 with each iteration. We can see this occur in the output:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "100\n", "90\n", "80\n", "70\n", "60\n", "50\n", "40\n", "30\n", "20\n", "10\n" ] } ], "source": [ "for i in range(100,0,-10):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When programming in Python, for loops often make use of the `range()` sequence type as its parameters for iteration." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "## For Loops using Sequential Data Types" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lists and other data sequence types can also be leveraged as iteration parameters in for loops. Rather than iterating through a `range()`, you can define a list and iterate through that list.\n", "\n", "We’ll assign a list to a variable, and then iterate through the list:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sharks = ['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem']\n", "\n", "for shark in sharks:\n", " print(shark)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this case, we are printing out each item in the list. Though we used the variable shark, we could have called the variable any other valid variable name and we would get the same output:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hammerhead\n", "great white\n", "dogfish\n", "frilled\n", "bullhead\n", "requiem\n" ] } ], "source": [ "sharks = ['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem']\n", "\n", "for shark in sharks:\n", " print(shark)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The output above shows that the `for` loop iterated through the list, and printed each item from the list per line." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lists and other sequence-based data types like strings and tuples are common to use with loops because they are iterable. You can combine these data types with range() to add items to a list, for example:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem', 'shark', 'shark', 'shark', 'shark', 'shark', 'shark']\n" ] } ], "source": [ "sharks = ['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem']\n", "\n", "for item in range(len(sharks)):\n", " sharks.append('shark')\n", "\n", "print(sharks)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, we have added a placeholder string of 'shark' for each item of the length of the sharks list.\n", "\n", "You can also use a `for` loop to construct a list from scratch:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "integers = []\n", "\n", "for i in range(10):\n", " integers.append(i)\n", "\n", "print(integers)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this example, the list `integers` is initialized as an empty list, but the for loop populates the list like so:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n" ] } ], "source": [ "integers = []\n", "\n", "for i in range(10):\n", " integers.append(i)\n", "\n", "print(integers)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly, we can iterate through strings:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "S\n", "a\n", "m\n", "m\n", "y\n" ] } ], "source": [ "sammy = 'Sammy'\n", "\n", "for letter in sammy:\n", " print(letter)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Iterating through tuples is done in the same format as iterating through lists or strings above." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When iterating through a dictionary, it’s important to keep the `key:value` structure in mind to ensure that you are calling the correct element of the dictionary. Here is an example that calls both the key and the value:" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "name: Sammy\n", "animal: shark\n", "color: blue\n", "location: ocean\n" ] } ], "source": [ "sammy_shark = {'name': 'Sammy', 'animal': 'shark', 'color': 'blue', 'location': 'ocean'}\n", "\n", "for key in sammy_shark:\n", " print(key + ': ' + sammy_shark[key])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When using dictionaries with `for` loops, the iterating variable corresponds to the keys of the dictionary, and `dictionary_variable[iterating_variable]` corresponds to the values. In the case above, the iterating variable key was used to stand for `key`, and `sammy_shark[key]` was used to stand for the values.\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Loops are often used to iterate and manipulate sequential data types." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Nested For Loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Loops can be nested in Python, as they can with other programming languages.\n", "\n", "A nested loop is a loop that occurs within another loop, structurally similar to nested if statements. These are constructed like so:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "for [first iterating variable] in [outer loop]: # Outer loop\n", " [do something] # Optional\n", " for [second iterating variable] in [nested loop]: # Nested loop\n", " [do something] \n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The program first encounters the outer loop, executing its first iteration. This first iteration triggers the inner, nested loop, which then runs to completion. Then the program returns back to the top of the outer loop, completing the second iteration and again triggering the nested loop. Again, the nested loop runs to completion, and the program returns back to the top of the outer loop until the sequence is complete or a break or other statement disrupts the process." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let’s implement a nested `for` loop so we can take a closer look. In this example, the outer loop will iterate through a list of integers called `num_list`, and the inner loop will iterate through a list of strings called `alpha_list`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "num_list = [1, 2, 3]\n", "alpha_list = ['a', 'b', 'c']\n", "\n", "for number in num_list:\n", " print(number)\n", " for letter in alpha_list:\n", " print(letter)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When we run this program, we’ll receive the following output:" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "a\n", "b\n", "c\n", "2\n", "a\n", "b\n", "c\n", "3\n", "a\n", "b\n", "c\n" ] } ], "source": [ "num_list = [1, 2, 3]\n", "alpha_list = ['a', 'b', 'c']\n", "\n", "for number in num_list:\n", " print(number)\n", " for letter in alpha_list:\n", " print(letter)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The output illustrates that the program completes the first iteration of the outer loop by printing `1`, which then triggers completion of the inner loop, printing `a`,`b`, `c` consecutively. Once the inner loop has completed, the program returns to the top of the outer loop, prints `2`, then again prints the inner loop in its entirety (`a`, `b`, `c`), etc." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Nested `for` loops can be useful for iterating through items within lists composed of lists. In a list composed of lists, if we employ just one for loop, the program will output each internal list as an item:" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['hammerhead', 'great white', 'dogfish']\n", "[0, 1, 2]\n", "[9.9, 8.8, 7.7]\n" ] } ], "source": [ "list_of_lists = [['hammerhead', 'great white', 'dogfish'],[0, 1, 2],[9.9, 8.8, 7.7]]\n", "\n", "for list in list_of_lists:\n", " print(list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In order to access each individual item of the internal lists, we’ll implement a nested `for` loop:" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hammerhead\n", "great white\n", "dogfish\n", "0\n", "1\n", "2\n", "9.9\n", "8.8\n", "7.7\n" ] } ], "source": [ "list_of_lists = [['hammerhead', 'great white', 'dogfish'],[0, 1, 2],[9.9, 8.8, 7.7]]\n", "\n", "for list in list_of_lists:\n", " for item in list:\n", " print(item)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When we utilize a nested for loop we are able to iterate over the individual items contained in the lists." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conclusion" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This tutorial went over how for loops work in Python and how to construct them. For loops continue to loop through a block of code provided a certain number of times." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 40 Example For Loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the next section I will provide 40 for loops. Each for loop is a different example of using for loops in cases the often come up in python data analysis." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Simple For Loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print the same thing 10 times" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hi\n", "hi\n", "hi\n", "hi\n", "hi\n", "hi\n", "hi\n", "hi\n", "hi\n", "hi\n" ] } ], "source": [ "for i in range(10):\n", " print(\"hi\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print the numbers 0-9" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n" ] } ], "source": [ "for i in range(10):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print the numbers 1-10" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n", "10\n" ] } ], "source": [ "for i in range(1,11):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print only the even numbers 1-10 combining a for loop with a if statement" ] }, { "cell_type": "code", "execution_count": 115, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "4\n", "6\n", "8\n", "10\n" ] } ], "source": [ "for i in range(1,11):\n", " if i%2==0:\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print the elements of a list" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "anna\n", "alex\n", "anselm\n", "david\n", "pam\n", "zhiwei\n", "ili\n", "shannon\n", "neil\n" ] } ], "source": [ "students = ['anna','alex','anselm','david','pam','zhiwei','ili','shannon','neil']\n", "for student in students:\n", " print(student)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print the elements of a list backwards" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "neil\n", "shannon\n", "ili\n", "zhiwei\n", "pam\n", "david\n", "anselm\n", "alex\n", "anna\n" ] } ], "source": [ "students = ['anna','alex','anselm','david','pam','zhiwei','ili','shannon','neil']\n", "for student in students[::-1]:\n", " print(student)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print the first four elements of a list" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "anna\n", "alex\n", "anselm\n", "david\n" ] } ], "source": [ "students = ['anna','alex','anselm','david','pam','zhiwei','ili','shannon','neil']\n", "for student in students[:4]:\n", " print(student)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print the entire list of students four times" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Careful with this one! Notice the small difference between the variables `students` (plural) and `student` (singular)." ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['anna', 'alex', 'anselm', 'david', 'pam', 'zhiwei', 'ili', 'shannon', 'neil']\n", "['anna', 'alex', 'anselm', 'david', 'pam', 'zhiwei', 'ili', 'shannon', 'neil']\n", "['anna', 'alex', 'anselm', 'david', 'pam', 'zhiwei', 'ili', 'shannon', 'neil']\n", "['anna', 'alex', 'anselm', 'david', 'pam', 'zhiwei', 'ili', 'shannon', 'neil']\n" ] } ], "source": [ "students = ['anna','alex','anselm','david','pam','zhiwei','ili','shannon','neil']\n", "for student in students[:4]:\n", " print(students)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Keep a counter (i) of how many times the loop repeated" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 anna\n", "1 alex\n", "2 anselm\n", "3 david\n", "4 pam\n", "5 zhiwei\n", "6 ili\n", "7 shannon\n", "8 neil\n" ] } ], "source": [ "students = ['anna','alex','anselm','david','pam','zhiwei','ili','shannon','neil']\n", "for i, student in enumerate(students):\n", " print(i, student)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Do something 10 times (make a random number) and don't use a named variable for iterator" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is kind of a python style thing. You can create a variable with a name just `_` (underscore). Since you would probably never name a variable something like that anywhere else in the code it can be good in `for` loops were you mostly care about repeating the same code a bunch of times and not iterating down the values of a list." ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.7457328618712995\n", "-0.4957320427978833\n", "1.7142799341183015\n", "1.4397353198097897\n", "-0.07644382036398782\n", "0.5061570560413113\n", "0.04191190760958118\n", "-1.2484947560962847\n", "-0.8951057795559447\n", "1.8120049924670218\n" ] } ], "source": [ "import numpy as np\n", "\n", "for _ in range(10):\n", " print(np.random.randn())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Iterate down two lists at the same time" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `zip` command takes to lists and combines them element by element. The lists need to be the same length!" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('anna', 'smith')\n", "('alex', 'johnson')\n", "('anselm', 'alexander')\n", "('david', 'baker')\n", "('pam', 'palmeri')\n", "('zhiwei', 'zoubok')\n", "('ili', 'weng')\n", "('shannon', 'foster')\n", "('neil', 'shields')\n" ] } ], "source": [ "firstname = ['anna','alex','anselm','david','pam','zhiwei','ili','shannon','neil']\n", "lastname = ['smith','johnson','alexander','baker','palmeri','zoubok','weng','foster','shields']\n", "for person in zip(firstname, lastname):\n", " print(person)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Iterating the entries in a dictionary by the key" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "123 Anna\n", "d131 Alex\n", "3f32 Anselm\n" ] } ], "source": [ "id_cards = {\"123\": \"Anna\", \"d131\": \"Alex\", \"3f32\": \"Anselm\"}\n", "for key in id_cards.keys():\n", " print(key,id_cards[key])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Iterating the values in a dictionary directly" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Anna\n", "Alex\n", "Anselm\n" ] } ], "source": [ "for name in id_cards.values():\n", " print(name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Keeping track of a result within a loop" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "All the examples so far have just repeated some simple block of code like printing something out. However, sometimes you want each iteration of the loop to compute something for you and store the result for further analysis. For example here we will square each number in a list and store it in a new list called results. Then we we plot the results." ] }, { "cell_type": "code", "execution_count": 99, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n" ] }, { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXQAAAD8CAYAAABn919SAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDMuMC4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvOIA7rQAAIABJREFUeJzt3Xl8lOW9/vHPl5AAYUlYwhYIi+yyJBDBta2APXpcwKVWVERFsT0e1566tb9j22Nbaj229lgXFJVFUYugVq1H645WJBAEWUR2CAECJCGQPfn+/shY0QMyJJk8mcn1fr14zcyTGebigVw8ued57tvcHRERiX7Ngg4gIiL1Q4UuIhIjVOgiIjFChS4iEiNU6CIiMUKFLiISI1ToIiIxQoUuIhIjVOgiIjGieUO+WadOnbx3794N+ZYiIlFv6dKle9w95WjPa9BC7927N1lZWQ35liIiUc/MtoTzPA25iIjECBW6iEiMUKGLiMQIFbqISIxQoYuIxAgVuohIjFChi4jEiLAK3cxuMbNVZvaZmc0zs5Zm1sfMFpvZejN7zswSIh1WRCTa7D1Qxq/+upqS8qqIv9dRC93MUoEbgUx3HwrEAZcAvwP+4O79gHxgaiSDiohEm/LKan789DKeXryFTXsORvz9wh1yaQ60MrPmQCKQC4wF5oe+PguYWP/xRESi169eWcUnm/Zx70XDGdK9XcTf76iF7u45wH3AVmqKvBBYChS4e2XoaduB1EiFFBGJNk8v3sLcj7dy3Xf7MiG9YeoxnCGX9sAEoA/QHWgNnBnuG5jZNDPLMrOsvLy8WgcVEYkWizfu5e6XVnH6wBRu+5dBDfa+4Qy5jAc2uXueu1cAC4BTgOTQEAxADyDncC929xnununumSk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hcFXCeQLj7YjObDyyj5uywbJrAFaO6UlREJEZEw5CLiIiEQYUuIhIjVOgiIjFChS4iEiNU6CIiMUKFLiISI1ToIiIxQoUuIhIj/j9OofX4/wvaQQAAAABJRU5ErkJggg==\n", "text/plain": [ "
" ] }, "metadata": { "needs_background": "light" }, "output_type": "display_data" } ], "source": [ "import matplotlib.pyplot as plt\n", "a = range(10)\n", "results = []\n", "for i in a:\n", " results.append(i**2)\n", "print(results)\n", "\n", "plt.plot(a,results)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print out the contents of a text file" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This will open a text file on your computer or jupyter hub instance and will print out each line of the file." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "myfile = 'something.txt'\n", "with open(myfile, 'r') as f:\n", " for line in f:\n", " print(line)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## For Loops Inside of For Loops (Nested)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print out a square using a nested loop" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice here that I used the underscore character for the `_i` and `_j` iterator variables." ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* * * * * * * * * * \n", "* * * * * * * * * * \n", "* * * * * * * * * * \n", "* * * * * * * * * * \n", "* * * * * * * * * * \n", "* * * * * * * * * * \n", "* * * * * * * * * * \n", "* * * * * * * * * * \n", "* * * * * * * * * * \n", "* * * * * * * * * * \n" ] } ], "source": [ "for _i in range(10): # rows\n", " for _j in range(10): # columns\n", " print(\"* \", end='') # this prevents a new line being printed each time\n", " print() # this only prints the new line at the end of each row" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Use the counter from the outer loop to change the inner loops" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "* \n", "* * \n", "* * * \n", "* * * * \n", "* * * * * \n", "* * * * * * \n", "* * * * * * * \n", "* * * * * * * * \n", "* * * * * * * * * \n" ] } ], "source": [ "for _i in range(10):\n", " for _j in range(_i): # add as many columns as we have experienced rows\n", " print(\"* \", end='')\n", " print()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Three nested loops? Why not!?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The more outer loops make squares of growing sides" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "----\n", "* \n", "----\n", "* * \n", "* * \n", "----\n", "* * * \n", "* * * \n", "* * * \n", "----\n", "* * * * \n", "* * * * \n", "* * * * \n", "* * * * \n", "----\n", "* * * * * \n", "* * * * * \n", "* * * * * \n", "* * * * * \n", "* * * * * \n", "----\n", "* * * * * * \n", "* * * * * * \n", "* * * * * * \n", "* * * * * * \n", "* * * * * * \n", "* * * * * * \n", "----\n", "* * * * * * * \n", "* * * * * * * \n", "* * * * * * * \n", "* * * * * * * \n", "* * * * * * * \n", "* * * * * * * \n", "* * * * * * * \n", "----\n", "* * * * * * * * \n", "* * * * * * * * \n", "* * * * * * * * \n", "* * * * * * * * \n", "* * * * * * * * \n", "* * * * * * * * \n", "* * * * * * * * \n", "* * * * * * * * \n", "----\n", "* * * * * * * * * \n", "* * * * * * * * * \n", "* * * * * * * * * \n", "* * * * * * * * * \n", "* * * * * * * * * \n", "* * * * * * * * * \n", "* * * * * * * * * \n", "* * * * * * * * * \n", "* * * * * * * * * \n", "----\n" ] } ], "source": [ "for _i in range(10):\n", " for _j in range(_i): # add as many columns as we have experienced rows\n", " for _k in range(_i):\n", " print(\"* \", end='')\n", " print()\n", " print('----')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## For Loops and Numpy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This section looks at the use of for loops in the context of a couple of common `numpy` functions." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print out a range from a numpy array" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This acts pretty much like the `range()` function described above. A `np.arange()` just returns a numpy array instead of a list." ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n" ] } ], "source": [ "import numpy as np\n", "for i in np.arange(0,10):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print out 20 steps between 0 and 10" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This does a normal for loop over a `np.linspace()` array. This function returns an numpy array between a start values (0) and end value (10) taking (20) steps. What is nice about this is that it figure how big the steps have to be so that you take two between the start and end value." ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.0\n", "0.5263157894736842\n", "1.0526315789473684\n", "1.5789473684210527\n", "2.1052631578947367\n", "2.631578947368421\n", "3.1578947368421053\n", "3.6842105263157894\n", "4.2105263157894735\n", "4.7368421052631575\n", "5.263157894736842\n", "5.789473684210526\n", "6.315789473684211\n", "6.842105263157895\n", "7.368421052631579\n", "7.894736842105263\n", "8.421052631578947\n", "8.947368421052632\n", "9.473684210526315\n", "10.0\n" ] } ], "source": [ "import numpy as np\n", "for i in np.linspace(0,10,20):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Using a nested loop to iterated over an array" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you have an array of arrays (sometimes called a matrix, although there is a specific matrix type in numpy), you might need to iterate over the elemnts:" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 2 3 \n", "4 5 6 \n" ] } ], "source": [ "x = np.array([[1,2,3],[4,5,6]])\n", "for _row in x:\n", " for _col in _row:\n", " print(_col,end=' ')\n", " print()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Interating over an array using indicies" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python is nice because you can iterate in a for loop directly over things in a collection like a list, dictionary or numpy array. However, sometimes you want to iterate by an index." ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 2 3 \n", "4 5 6 \n" ] } ], "source": [ "x = np.array([[1,2,3],[4,5,6]])\n", "rows, cols = x.shape\n", "for i in range(rows):\n", " for j in range(cols):\n", " print(x[i][j],end=' ') # here we are looking up the value in the array using our indicies\n", " print()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## For Loops and Pandas" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This section looks at the use of for loops in the context of a couple of common `pandas` data munging operations. For these examples, I am loading a .csv file hosted on the class webpage on salary of professors that we encountered in a previous homework." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Iterating over columns" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "First let's print out each of the columns in this data frame" ] }, { "cell_type": "code", "execution_count": 104, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "salary\n", "gender\n", "departm\n", "years\n", "age\n", "publications\n" ] } ], "source": [ "import pandas as pd\n", "salary_data = pd.read_csv('http://gureckislab.org/courses/fall19/labincp/data/salary.csv')\n", "for col in salary_data.columns:\n", " print(col)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Iterating over rows" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dataframes have a couple of ways you can iterate over the rows. The best is the `.iterrows()` method available on any data frame which is a proper [iterator](https://treyhunner.com/2018/06/how-to-make-an-iterator-in-python/) similar to what you get using the `enumerate()` function we explored above. If you wanted to print out the entire data frame you can just delete the `.head(n=3)` part of the command (i.e., `salary_data.iterrows()`." ] }, { "cell_type": "code", "execution_count": 109, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 salary 86285\n", "gender 0\n", "departm bio\n", "years 26\n", "age 64\n", "publications 72\n", "Name: 0, dtype: object\n", "---\n", "1 salary 77125\n", "gender 0\n", "departm bio\n", "years 28\n", "age 58\n", "publications 43\n", "Name: 1, dtype: object\n", "---\n", "2 salary 71922\n", "gender 0\n", "departm bio\n", "years 10\n", "age 38\n", "publications 23\n", "Name: 2, dtype: object\n", "---\n" ] } ], "source": [ "import pandas as pd\n", "salary_data = pd.read_csv('http://gureckislab.org/courses/fall19/labincp/data/salary.csv')\n", "for index, row in salary_data.head(n=3).iterrows():\n", " print(index, row)\n", " print('---')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Iterating over groups" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One of the most useful functions of pandas dataframes is the `groupby` operation which divides up a larger dataframe into smaller groups based on the value of one or more columns. This is ideal for psychological data analysis because you might want to divide up your data based on trial type, participant number, etc... After you form the groups it is often useful to iterate over the groups to do additional analyses." ] }, { "cell_type": "code", "execution_count": 113, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "bio\n", "-----\n", " salary gender departm years age publications\n", "0 86285 0 bio 26.0 64.0 72\n", "1 77125 0 bio 28.0 58.0 43\n", "2 71922 0 bio 10.0 38.0 23\n", "3 70499 0 bio 16.0 46.0 64\n", "4 66624 0 bio 11.0 41.0 23\n", "5 64451 0 bio 23.0 60.0 44\n", "6 64366 0 bio 23.0 53.0 22\n", "7 59344 0 bio 5.0 40.0 11\n", "8 58560 0 bio 8.0 38.0 8\n", "9 58294 0 bio 20.0 50.0 12\n", "10 56092 0 bio 2.0 40.0 4\n", "11 54452 0 bio 13.0 43.0 7\n", "12 54269 0 bio 26.0 56.0 12\n", "13 55125 0 bio 8.0 38.0 9\n", "68 59139 1 bio 8.0 38.0 23\n", "69 52968 1 bio 18.0 48.0 32\n", "\n", "chem\n", "-----\n", " salary gender departm years age publications\n", "14 97630 0 chem 34.0 64.0 43\n", "15 82444 0 chem 31.0 61.0 42\n", "16 76291 0 chem 29.0 65.0 33\n", "17 75382 0 chem 26.0 56.0 39\n", "18 64762 0 chem 25.0 NaN 29\n", "19 62607 0 chem 20.0 45.0 34\n", "20 60373 0 chem 26.0 56.0 43\n", "21 58892 0 chem 18.0 48.0 21\n", "22 47021 0 chem 4.0 34.0 12\n", "23 44687 0 chem 4.0 34.0 19\n", "70 55949 1 chem 4.0 34.0 12\n", "\n", "geol\n", "-----\n", " salary gender departm years age publications\n", "24 104828 0 geol NaN 50.0 44\n", "25 71456 0 geol 11.0 41.0 32\n", "26 65144 0 geol 7.0 37.0 12\n", "27 52766 0 geol 4.0 38.0 32\n", "\n", "math\n", "-----\n", " salary gender departm years age publications\n", "62 82142 0 math 9.0 39.0 9\n", "63 70509 0 math 23.0 53.0 7\n", "64 60320 0 math 14.0 44.0 7\n", "65 55814 0 math 8.0 38.0 6\n", "66 53638 0 math 4.0 42.0 8\n", "67 53517 2 math 5.0 35.0 5\n", "75 61885 1 math 23.0 60.0 9\n", "76 49542 1 math 3.0 33.0 5\n", "\n", "neuro\n", "-----\n", " salary gender departm years age publications\n", "28 112800 0 neuro 14.0 44.0 33\n", "29 105761 0 neuro 9.0 39.0 30\n", "30 92951 0 neuro 11.0 41.0 20\n", "31 86621 0 neuro 19.0 49.0 10\n", "32 85569 0 neuro 20.0 46.0 35\n", "33 83896 0 neuro 10.0 40.0 22\n", "34 79735 0 neuro 11.0 41.0 32\n", "35 71518 0 neuro 7.0 37.0 34\n", "36 68029 0 neuro 15.0 45.0 33\n", "37 66482 0 neuro 14.0 44.0 42\n", "38 61680 0 neuro 18.0 48.0 20\n", "39 60455 0 neuro 8.0 38.0 49\n", "40 58932 0 neuro 11.0 41.0 49\n", "71 58893 1 neuro 10.0 35.0 4\n", "72 53662 1 neuro 1.0 31.0 3\n", "\n", "physics\n", "-----\n", " salary gender departm years age publications\n", "54 96936 0 physics 15.0 50.0 17\n", "55 83216 0 physics 11.0 37.0 19\n", "56 72044 0 physics 2.0 32.0 16\n", "57 64048 0 physics 23.0 53.0 4\n", "58 58888 0 physics 26.0 56.0 7\n", "59 58744 0 physics 20.0 50.0 9\n", "60 55944 0 physics 21.0 51.0 8\n", "61 54076 0 physics 19.0 49.0 12\n", "\n", "stat\n", "-----\n", " salary gender departm years age publications\n", "41 106412 0 stat 23.0 53.0 29\n", "42 86980 0 stat 23.0 53.0 42\n", "43 78114 0 stat 8.0 38.0 24\n", "44 74085 0 stat 11.0 41.0 33\n", "45 72250 0 stat 26.0 56.0 9\n", "46 69596 0 stat 20.0 50.0 18\n", "47 65285 0 stat 20.0 50.0 15\n", "48 62557 0 stat 28.0 58.0 14\n", "49 61947 0 stat 22.0 58.0 17\n", "50 58565 0 stat 29.0 59.0 11\n", "51 58365 0 stat 18.0 48.0 21\n", "52 53656 0 stat 2.0 32.0 4\n", "53 51391 0 stat 5.0 35.0 8\n", "73 57185 1 stat 9.0 39.0 7\n", "74 52254 1 stat 2.0 32.0 9\n", "\n" ] } ], "source": [ "import pandas as pd\n", "salary_data = pd.read_csv('http://gureckislab.org/courses/fall19/labincp/data/salary.csv')\n", "\n", "grouped = salary_data.groupby(\"departm\")\n", "\n", "for name, group in grouped:\n", " print(name)\n", " print('-----')\n", " print(group)\n", " print()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Iterating over muliple groups" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can group not just on a single column but combinations of multiple combinations." ] }, { "cell_type": "code", "execution_count": 114, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('bio', 0)\n", "-----\n", " salary gender departm years age publications\n", "0 86285 0 bio 26.0 64.0 72\n", "1 77125 0 bio 28.0 58.0 43\n", "2 71922 0 bio 10.0 38.0 23\n", "3 70499 0 bio 16.0 46.0 64\n", "4 66624 0 bio 11.0 41.0 23\n", "5 64451 0 bio 23.0 60.0 44\n", "6 64366 0 bio 23.0 53.0 22\n", "7 59344 0 bio 5.0 40.0 11\n", "8 58560 0 bio 8.0 38.0 8\n", "9 58294 0 bio 20.0 50.0 12\n", "10 56092 0 bio 2.0 40.0 4\n", "11 54452 0 bio 13.0 43.0 7\n", "12 54269 0 bio 26.0 56.0 12\n", "13 55125 0 bio 8.0 38.0 9\n", "\n", "('bio', 1)\n", "-----\n", " salary gender departm years age publications\n", "68 59139 1 bio 8.0 38.0 23\n", "69 52968 1 bio 18.0 48.0 32\n", "\n", "('chem', 0)\n", "-----\n", " salary gender departm years age publications\n", "14 97630 0 chem 34.0 64.0 43\n", "15 82444 0 chem 31.0 61.0 42\n", "16 76291 0 chem 29.0 65.0 33\n", "17 75382 0 chem 26.0 56.0 39\n", "18 64762 0 chem 25.0 NaN 29\n", "19 62607 0 chem 20.0 45.0 34\n", "20 60373 0 chem 26.0 56.0 43\n", "21 58892 0 chem 18.0 48.0 21\n", "22 47021 0 chem 4.0 34.0 12\n", "23 44687 0 chem 4.0 34.0 19\n", "\n", "('chem', 1)\n", "-----\n", " salary gender departm years age publications\n", "70 55949 1 chem 4.0 34.0 12\n", "\n", "('geol', 0)\n", "-----\n", " salary gender departm years age publications\n", "24 104828 0 geol NaN 50.0 44\n", "25 71456 0 geol 11.0 41.0 32\n", "26 65144 0 geol 7.0 37.0 12\n", "27 52766 0 geol 4.0 38.0 32\n", "\n", "('math', 0)\n", "-----\n", " salary gender departm years age publications\n", "62 82142 0 math 9.0 39.0 9\n", "63 70509 0 math 23.0 53.0 7\n", "64 60320 0 math 14.0 44.0 7\n", "65 55814 0 math 8.0 38.0 6\n", "66 53638 0 math 4.0 42.0 8\n", "\n", "('math', 1)\n", "-----\n", " salary gender departm years age publications\n", "75 61885 1 math 23.0 60.0 9\n", "76 49542 1 math 3.0 33.0 5\n", "\n", "('math', 2)\n", "-----\n", " salary gender departm years age publications\n", "67 53517 2 math 5.0 35.0 5\n", "\n", "('neuro', 0)\n", "-----\n", " salary gender departm years age publications\n", "28 112800 0 neuro 14.0 44.0 33\n", "29 105761 0 neuro 9.0 39.0 30\n", "30 92951 0 neuro 11.0 41.0 20\n", "31 86621 0 neuro 19.0 49.0 10\n", "32 85569 0 neuro 20.0 46.0 35\n", "33 83896 0 neuro 10.0 40.0 22\n", "34 79735 0 neuro 11.0 41.0 32\n", "35 71518 0 neuro 7.0 37.0 34\n", "36 68029 0 neuro 15.0 45.0 33\n", "37 66482 0 neuro 14.0 44.0 42\n", "38 61680 0 neuro 18.0 48.0 20\n", "39 60455 0 neuro 8.0 38.0 49\n", "40 58932 0 neuro 11.0 41.0 49\n", "\n", "('neuro', 1)\n", "-----\n", " salary gender departm years age publications\n", "71 58893 1 neuro 10.0 35.0 4\n", "72 53662 1 neuro 1.0 31.0 3\n", "\n", "('physics', 0)\n", "-----\n", " salary gender departm years age publications\n", "54 96936 0 physics 15.0 50.0 17\n", "55 83216 0 physics 11.0 37.0 19\n", "56 72044 0 physics 2.0 32.0 16\n", "57 64048 0 physics 23.0 53.0 4\n", "58 58888 0 physics 26.0 56.0 7\n", "59 58744 0 physics 20.0 50.0 9\n", "60 55944 0 physics 21.0 51.0 8\n", "61 54076 0 physics 19.0 49.0 12\n", "\n", "('stat', 0)\n", "-----\n", " salary gender departm years age publications\n", "41 106412 0 stat 23.0 53.0 29\n", "42 86980 0 stat 23.0 53.0 42\n", "43 78114 0 stat 8.0 38.0 24\n", "44 74085 0 stat 11.0 41.0 33\n", "45 72250 0 stat 26.0 56.0 9\n", "46 69596 0 stat 20.0 50.0 18\n", "47 65285 0 stat 20.0 50.0 15\n", "48 62557 0 stat 28.0 58.0 14\n", "49 61947 0 stat 22.0 58.0 17\n", "50 58565 0 stat 29.0 59.0 11\n", "51 58365 0 stat 18.0 48.0 21\n", "52 53656 0 stat 2.0 32.0 4\n", "53 51391 0 stat 5.0 35.0 8\n", "\n", "('stat', 1)\n", "-----\n", " salary gender departm years age publications\n", "73 57185 1 stat 9.0 39.0 7\n", "74 52254 1 stat 2.0 32.0 9\n", "\n" ] } ], "source": [ "import pandas as pd\n", "salary_data = pd.read_csv('http://gureckislab.org/courses/fall19/labincp/data/salary.csv')\n", "\n", "grouped = salary_data.groupby([\"departm\",\"gender\"])\n", "\n", "for name, group in grouped:\n", " print(name)\n", " print('-----')\n", " print(group)\n", " print()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reading in an entire directory of files" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sometimes you need to read in an process individual files in a folder. This code snippet for instance reads all the .csv files in a particular folder into a pandas dataframe and concatenates them." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "data_path = './myfile/'\n", "files = os.listdir(data_path)\n", "frames = []\n", "for data_file in files:\n", " if data_file[-3:] == 'csv':\n", " df = pd.read_csv(data_path+data_file)\n", " frames.append(df)\n", "alldata_df = pd.concat(frames)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## For Loops and Seaborn" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This section looks at the use of for loops in the context of plotting with `seaborn`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Plotting to subpanels of a matplotlib figure with a for loop" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig,ax = plt.subplots(7,3,figsize=(12,24))\n", "ax = ax.ravel()\n", "for i,s in enumerate(subs):\n", " part_df=all_df[all_df.participant==s]\n", " p1=sns.regplot(x='angle',y='trialResp.rt',data=part_df,ax=ax[i])\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## For Loops and Matplotlib" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "celltoolbar": "Tags", "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.7.3" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": { "height": "calc(100% - 180px)", "left": "10px", "top": "150px", "width": "303.796875px" }, "toc_section_display": true, "toc_window_display": true } }, "nbformat": 4, "nbformat_minor": 2 }