python-for-data-analysis.ipynb 22.1 KB
Newer Older
George Mount's avatar
George Mount committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python for Data Analysis, pt. 1\n",
    "## Manipulating DataFrames\n",
    "\n",
    "I probably don't have to tell you that data professionals spend a *lot* of time preparing and cleaning data.\n",
    "\n",
    "Python can help you automate and reduce errors in this work! But it takes practice.\n",
    "\n",
    "Let's look at the `pandas` way of performing common data manipulation tasks: \n",
    "\n",
    "- Adding and dropping columns\n",
    "- Sorting and filtering\n",
    "- Merging DataFrames (think `VLOOKUP()`)\n",
    "- Grouping DataFrames (think PivotTables)\n",
    "\n",
    "We should read in our `state-populations.csv` file from the `data` folder. Do you remember how? "
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
26 27 28
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
29 30 31 32 33 34
   "source": [
    "state_pop = pd.read_csv('data/state-populations.csv')"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
35
   "execution_count": null,
George Mount's avatar
George Mount committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
   "metadata": {},
   "outputs": [],
   "source": [
    "# Don't forget to import!\n",
    "import pandas as pd\n",
    "state_pop = pd.read_csv('data/state-populations.csv')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "How do we get the first 5 rows again?"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
53
   "execution_count": null,
George Mount's avatar
George Mount committed
54 55 56
   "metadata": {
    "tags": []
   },
George Mount's avatar
George Mount committed
57
   "outputs": [],
George Mount's avatar
George Mount committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
   "source": [
    "state_pop.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Selecting, adding, dropping and renaming columns\n",
    "\n",
    "When we work with data we frequently need to derive new columns based on existing columns. Conversely, we may also want to drop unhelpful columns or only select certain columns. \n",
    "\n",
    "### Selecting columns\n",
    "\n",
    "We will use square brackets `[]` to select certain columns in a DataFrame -- but with a twist (color you surprised yet?)...\n",
    "\n",
    "Earlier we mentioned that `pandas` will attempt to convert one-dimensional data structures into Series. Let's see that in action: we will select *just* the `Population` column from our DataFrame:\n"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
79 80 81
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
   "source": [
    "# Pull specific columns by name with brackets\n",
    "df = state_pop['Population']\n",
    "\n",
    "# What kind of data structure is this? \n",
    "type(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we wanted to keep this as a DataFrame (which we should, if we aren't positive that we don't want extra columns added to this variable!), we can use *double-bracket* [[]] notation:"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
99 100 101
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
   "source": [
    "# We can keep this as a DataFrame and not a Series\n",
    "# by using two brackets instead of one 🤔\n",
    "df = state_pop[['Population']]\n",
    "\n",
    "# What kind of data structure is this? \n",
    "type(df) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With that quirk out of the way, let's select both the `Population` and `Year` columns: "
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
120 121 122
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
   "source": [
    "state_pop[['Population','Year']]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Deleting columns\n",
    "\n",
    "We can also drop specific columns using the `drop()` method.\n",
    "\n",
    "Fortunately, we don't have to worry about double-bracket weirdness this time around, but we do have to worry about the so-called \"axis.\"\n",
    "\n",
    "In a DataFrame, rows are considered \"axis 0\" and columns are considered \"axis 1.\"\n",
    "\n",
    "![DataFrame axes](images/axes.png)\n",
    "\n",
    "We will provide `drop()` the name of the labels we want to drop, and whether those labels are on \"axis 0\" or \"axis 1\"\n"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
146 147 148
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
   "source": [
    "# Drop name from columns (i.e. axis 1)\n",
    "df = state_pop.drop('name',axis=1)\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Per usual, `drop()` has several optional arguments. [Check the documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html) for more details."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Creating new columns\n",
    "\n",
    "Ok, we've selected and removed columns, but what about adding new ones?\n",
    "\n",
    "We will lean on bracket `[]` notation to do so, using the following structure:\n",
    "\n",
    "`df['new column name'] = new column contents here`\n",
    "\n",
    "Let's give it a try:\n"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
179 180 181
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
   "source": [
    "# Create a new column in state_pop\n",
    "state_pop['new_column'] = 'Hello world'\n",
    "\n",
    "state_pop.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's a wildly unhelpful new column. \n",
    "\n",
    "Let's put something more useful in its place, such as calculating population density (total population divided by size):"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
200 201 202
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
   "source": [
    "# Recalculate new_column as density\n",
    "state_pop['new_column'] = state_pop['Population']/state_pop['Size']\n",
    "state_pop.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Renaming columns\n",
    "\n",
    "That's better! But `new_column` isn't a very helpful column name. We can rename it using the following format:\n",
    "\n",
    "```\n",
    "df = df.rename(columns = {'old column name':'new column name'})\n",
    "```\n",
    "Let's give it a try:\n"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
225 226 227
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
   "source": [
    "state_pop = state_pop.rename(columns = {'new_column':'Density'})\n",
    "state_pop.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The above notation is an example of a Python *dictionary*. This is another important core data structure of Python and one to check out as you continue learning the language."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Drill\n",
    "\n",
    "The `data` folder contains a workbook called `wholesale.xlsx`.  This is a real-life dataset from [UC Irvine's Machine Learning Repository](http://archive.ics.uci.edu/ml/datasets/Wholesale+customers) (a good site to bookmark!).\n",
    "\n",
    "Read in the `data` worksheet from this workbook below as a DataFrame called `wholesale` and explore it:"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
253 254 255
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
   "source": [
    "import pandas as pd\n",
    "wholesale = pd.read_excel('data/wholesale.xlsx',sheet_name='data')\n",
    "wholesale.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create a column `Scratch` which is a total of the `Fresh` and `Frozen` columns. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "___ = ___+___'Frozen'\n",
    "wholesale.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, delete this column. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "wholesale = wholesale.___\n",
    "wholesale.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Depending on what columns you want to add and drop, the above code will help you build automated pipelines for data cleanup."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Sorting a DataFrame\n",
    "\n",
    "Our data is currently sorted A-Z by `name`. What if we wanted to sort it instead by `Population`?\n",
    "\n",
    "We can do so with `sort_values()`, using the below notation:\n",
    "\n",
    "```      \n",
    "df.sort_values(by=['col_name'])\n",
    "```\n",
    "\n",
    "Let's do it!\n"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
322
   "execution_count": null,
George Mount's avatar
George Mount committed
323 324 325
   "metadata": {
    "code_folding": []
   },
George Mount's avatar
George Mount committed
326
   "outputs": [],
George Mount's avatar
George Mount committed
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
   "source": [
    "# Sort our DataFrame by Population\n",
    "state_pop.sort_values(by=['Population'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our data is sorted ascendingly (i.e. A-Z, low-to-high) by default. \n",
    "\n",
    "As a refresher on how sorting works, check out the below table.\n",
    "\n",
    "| Data type | Ascending | Descending |\n",
    "| --------- | --------- | ---------- |\n",
    "| Number    | `1 … 9`   | `9 … 1`    |\n",
    "| String    | `A … Z`   | `Z … A`    |\n",
    "\n",
    " \n",
    "\n",
    "We can sort descending by including `ascending=False` in our `sort_values()` statement:\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
353 354 355
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
   "source": [
    "state_pop.sort_values(by=['Population'], ascending=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It's also possible to sort by multiple columns, similar to how you might in Excel with Custom Sort.\n",
    "\n",
    "![Excel custom sort menu](images/custom-sort.png)\n"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
371 372 373
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
   "source": [
    "# Filter by multiple columns\n",
    "state_pop.sort_values(by=['Year','name'], ascending=[False,True])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Drill\n",
    "\n",
    "Sort `wholesale` by `Channel`, low to high, then `Region`, high to low. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Filter by multiple columns\n",
    "___"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Filtering a DataFrame\n",
    "\n",
    "Filtering in Excel is quite easy: we just place a filter over our data and can click through the conditions:\n",
    "\n",
    "![Filtering in Excel](images/excel-filter.png)\n",
    "\n",
    "In Python we will need to code this, but if you've used conditional logic before this should make intuitive sense.\n",
    "\n",
    "Our steps for filtering a DataFrames will be:\n",
    "\n",
    "1. Create a series of `True`/`False` flags indicating whether each row meets some criteria\n",
    "2. Filter the rows from our DataFrame where those criteria evaluate to `True`. \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Remember our comparison operators from back in the first section? We'll use them again here.\n",
    "\n",
    "| Operator | Meaning                  |\n",
    "| -------- | ------------------------ |\n",
    "| `>`      | Greater than             |\n",
    "| `<`      | Less than                |\n",
    "| `>=`     | Greater than or equal to |\n",
    "| `<=`     | Less than or equal to    |\n",
    "| `!=`     | Not equal to             |\n",
    "| `==`     | Equal to                 |"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this example, let's find the entries where the population exceeds 1 million."
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
441 442 443
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
444 445 446
   "source": [
    "# Set to True the records greater than 1 million\n",
    "one_mill = state_pop['Population'] > 1000000\n",
George Mount's avatar
George Mount committed
447 448 449 450 451 452 453 454 455 456
    "one_mill"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "type(one_mill)"
George Mount's avatar
George Mount committed
457 458 459 460 461 462 463 464 465 466 467
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can now filter our DataFrame by passing this series of `True`/`False` flags into it with brackets `[]`: "
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
468 469 470
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
471 472 473
   "source": [
    "# Filter our state_pop DataFrame by our one_mill Series\n",
    "state_pop_one_mill = state_pop[one_mill]\n",
George Mount's avatar
George Mount committed
474 475 476 477 478 479 480 481 482 483
    "state_pop.shape\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "state_pop_one_mill.shape"
George Mount's avatar
George Mount committed
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We are only filtering the *rows* of our DataFrame. These results will not affect the columns."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's try one more. We would just like to include the data from the year 2015.\n",
    "\n",
    "Remember the notation kicker with testing for equality! "
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
504 505 506
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
   "source": [
    "# Not == but = \n",
    "pop_2015 = state_pop['Year'] == 2015\n",
    "\n",
    "state_pop_2015 = state_pop[pop_2015]\n",
    "state_pop_2015.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can combine conditional operators into *and*/*or* statements using the following notation:\n",
    "\n",
    "\n",
    "| Operator    | Meaning       |\n",
    "| ----------- | ------------- |\n",
    "| `X & Y` | `X` *and* `Y` |\n",
    "| `X \\| Y` | `X` *or* `Y`  |\n"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
530 531 532
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
   "source": [
    "# Get rows with population >1 million AND in 2015\n",
    "one_mill_pop_2015 = state_pop[one_mill & pop_2015]\n",
    "one_mill_pop_2015.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[For more ways to filter a DataFrame, check out this blog post](https://www.listendata.com/2019/07/how-to-filter-pandas-dataframe.html)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Drill\n",
    "\n",
    "Filter the records of `wholesale` that are either in Channel 1 or Region 3. "
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
557 558 559
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
   "source": [
    "channel_1 = wholesale___ ___ 1\n",
    "region_3 = wholesale___ ___ 3\n",
    "\n",
    "wholesale_filtered = wholesale[___ ___ region_3]\n",
    "wholesale_filtered.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Grouping DataFrames\n",
    "\n",
    "Let's say you wanted to know the average population of each state across all years.\n",
    "\n",
    "\n",
    "An easy way of doing this in Excel would be with a PivotTable. You could place your *state* along the Rows and then set the value of population to get the average:\n",
    "\n",
    "![Example of a PivotTable](images/pivot.gif)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can code the equivalent of a PivotTable in `pandas` using `groupby()`. \n"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
591 592 593
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
   "source": [
    "state_pop.groupby('name')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "However, simply grouping our DataFrame by `name` doesn't do much for us. This would be like placing data into the Rows area without any data in the Values area. \n",
    "\n",
    "![Pivot table with no values](images/pivot-no-values.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When you drag a column to the Values area, you have different options for summarizing, or *aggregating* the data:\n",
    "\n",
    "![Changing aggregation type in a PivotTable](images/pivot-aggregation.gif)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In Python, we will specify what field to group by, then what field to summarize and how using the following notation:\n",
    "\n",
    "`df.groupby('row')[['value']].agg_type()`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Method    | Aggregation type |\n",
    "| --------- | ---------------- |\n",
    "| `sum()`   | Sum              |\n",
    "| `count()` | Count values     |\n",
    "| `mean()`  | Average          |\n",
    "| `max()`   | Highest value    |\n",
    "| `min()`   | Lowest value     |\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
641
   "execution_count": null,
George Mount's avatar
George Mount committed
642 643 644
   "metadata": {
    "tags": []
   },
George Mount's avatar
George Mount committed
645
   "outputs": [],
George Mount's avatar
George Mount committed
646 647 648 649 650 651 652 653 654 655 656 657 658 659
   "source": [
    "# Average population by state \n",
    "state_pop.groupby('name')[['Population']].mean()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's use the same notation to get the smallest population for each year: "
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
660 661 662
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
   "source": [
    "state_pop.groupby('Year')[['Population']].min()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Drill \n",
    "\n",
    "For the `wholesale` dataset, group the data to get average `Milk` sales by `Region`, then the most `Frozen` sales for each `Channel`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Average milk sales by region \n",
    "wholesale.groupby(___)[['Milk']].___"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Most frozen sales for each channel\n",
    "wholesale.groupby('Channel')___.max()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Merging DataFrames\n",
    "\n",
    "The `data` folder has an Excel workbook called `census-divisions.xlsx`. Let's read that in."
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
707 708 709
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
   "source": [
    "census = pd.read_excel('data/census-divisions.xlsx')\n",
    "census.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What if we wanted to pull the state postal code, region and divisons from `census` into our `population` DataFrame? \n",
    "\n",
    "Back in Excel, we could do this with a `VLOOKUP()`. \n",
    "\n",
    "![VLOOKUP in Excel](images/vlookup.png)\n",
    "\n",
    "In Python we can use `merge()`.  This has a [*lot* of optional arguments](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html), but the basic notation will look like this:\n",
    "\n",
    "`df1.merge(df2)`\n",
    "\n",
    "You can think of this as us looking up data *from* `df2` *into* `df1`. \n",
    "\n",
    "In this case let's look up data *from* `census` *into* `state_pop`:"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
736 737 738
   "execution_count": null,
   "metadata": {},
   "outputs": [],
George Mount's avatar
George Mount committed
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
   "source": [
    "state_pop.merge(census)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By default, *all* columns from the second DataFrame are \"looked up\" into the first. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## DRILL\n",
    "\n",
    "The `wholesale` workbook has another worksheet called `regions` and `channels` containing descriptions for `Region` and `Channel.`\n",
    "\n",
    "Read these DataFrames into Excel and then merge them into `wholesale`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "regions = ___\n",
    "regions.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Merge the DataFrames\n",
    "wholesale.merge(regions)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exporting DataFrames to Excel\n",
    "\n",
    "You may decide you want to conduct your data analysis in Python, and then write the results back to Excel.\n",
    "\n",
    "You can do this with the [`to_excel()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html) method: "
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
794
   "execution_count": null,
George Mount's avatar
George Mount committed
795 796 797 798 799 800 801 802
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
George Mount's avatar
George Mount committed
803
   "execution_count": null,
George Mount's avatar
George Mount committed
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write our state_pop DataFrame to Excel\n",
    "# We can specify the worksheet name too\n",
    "state_pop.to_excel('state_pop_export.xlsx',sheet_name='analysis')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## DRILL\n",
    "\n",
    "Write the results of `wholesale` to `wholesale-work.xlsx` in the `data` folder of this section."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "____.___('___/wholesale-work___')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Conclusion\n",
    "\n",
    "Were you able to see the connections between data manipulation tasks that you do every day in Excel and how they relate to `pandas`? \n",
    "\n",
    "For a master class in using `pandas` to clean and reshape data, check out the O'Reilly book [*Python for Data Analysis, 2nd Edition*](https://learning.oreilly.com/library/view/python-for-data/9781491957653/). "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Questions about manipulating data in `pandas`?"
   ]
  },
  {
   "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",
George Mount's avatar
George Mount committed
872
   "version": "3.7.4"
George Mount's avatar
George Mount committed
873 874 875 876 877
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}