index.html 53.5 KB
Newer Older
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 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 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 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 253 254 255 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 322 323 324 325 326 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 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 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 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 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 591 592 593 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 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 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 707 708 709 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 736 737 738 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 794 795 796 797 798 799 800 801 802 803 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 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="last-modified" content="2017-08-04 00:20:27 +0200">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- meta "search-domain" used for google site search function google_search() -->
    <meta name="search-domain" value="/swc-releases/2017.08/python-novice-inflammation">
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="../assets/css/lesson.css" />
    
    <link rel="shortcut icon" type="image/x-icon" href="/favicon-swc.ico" />
    
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
	<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
	<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
	<![endif]-->
    <title>Programming with Python: Analyzing Patient Data</title>
  </head>
  <body>
    <div class="container">
      
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>

      
      

      
      <a class="navbar-brand" href="../">Home</a>

    </div>
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">

	
        <li><a href="../conduct/">Code of Conduct</a></li>

	
        
        <li><a href="../setup/">Setup</a></li>
        <li class="dropdown">
          <a href="../" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Episodes <span class="caret"></span></a>
          <ul class="dropdown-menu">
            
            <li><a href="../01-numpy/">Analyzing Patient Data</a></li>
            
            <li><a href="../02-loop/">Repeating Actions with Loops</a></li>
            
            <li><a href="../03-lists/">Storing Multiple Values in Lists</a></li>
            
            <li><a href="../04-files/">Analyzing Data from Multiple Files</a></li>
            
            <li><a href="../05-cond/">Making Choices</a></li>
            
            <li><a href="../06-func/">Creating Functions</a></li>
            
            <li><a href="../07-errors/">Errors and Exceptions</a></li>
            
            <li><a href="../08-defensive/">Defensive Programming</a></li>
            
            <li><a href="../09-debugging/">Debugging</a></li>
            
            <li><a href="../10-cmdline/">Command-Line Programs</a></li>
            
	    <li role="separator" class="divider"></li>
            <li><a href="../aio/">All in one page (Beta)</a></li>
          </ul>
        </li>
	

	
	
        <li class="dropdown">
          <a href="../" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Extras <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="../reference/">Reference</a></li>
            
            <li><a href="../about/">About</a></li>
            
            <li><a href="../discuss/">Discussion</a></li>
            
            <li><a href="../figures/">Figures</a></li>
            
            <li><a href="../guide/">Instructor Notes</a></li>
            
          </ul>
        </li>
	

	
        <li><a href="../license/">License</a></li>
	
	<li><a href="/edit/gh-pages/_episodes/01-numpy.md">Improve this page <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a></li>
	
      </ul>
      <form class="navbar-form navbar-right" role="search" id="search" onsubmit="google_search(); return false;">
        <div class="form-group">
          <input type="text" id="google-search" placeholder="Search..." aria-label="Google site search">
        </div>
      </form>
    </div>
  </div>
</nav>


<div class="row">
  <div class="col-md-1">
    <h3>
      
      <a href="../"><span class="glyphicon glyphicon-menu-up" aria-hidden="true"></span><span class="sr-only">lesson home</span></a>
      
    </h3>
  </div>
  <div class="col-md-10">
    
    <h3 class="maintitle"><a href="../">Programming with Python</a></h3>
    
  </div>
  <div class="col-md-1">
    <h3>
      
      <a href="../02-loop/"><span class="glyphicon glyphicon-menu-right" aria-hidden="true"></span><span class="sr-only">next episode</span></a>
      
    </h3>
  </div>
</div>

<article>
<div class="row">
  <div class="col-md-1">
  </div>
  <div class="col-md-10">
    <h1 class="maintitle">Analyzing Patient Data</h1>
  </div>
  <div class="col-md-1">
  </div>
</div>


<blockquote class="objectives">
  <h2>Overview</h2>

  <div class="row">
    <div class="col-md-3">
      <strong>Teaching:</strong> 30 min
      <br/>
      <strong>Exercises:</strong> 0 min
    </div>
    <div class="col-md-9">
      <strong>Questions</strong>
      <ul>
	
	<li><p>How can I process tabular data files in Python?</p>
</li>
	
      </ul>
    </div>
  </div>

  <div class="row">
    <div class="col-md-3">
    </div>
    <div class="col-md-9">
      <strong>Objectives</strong>
      <ul>
	
	<li><p>Explain what a library is, and what libraries are used for.</p>
</li>
	
	<li><p>Import a Python library and use the functions it contains.</p>
</li>
	
	<li><p>Read tabular data from a file into a program.</p>
</li>
	
	<li><p>Assign values to variables.</p>
</li>
	
	<li><p>Select individual values and subsections from data.</p>
</li>
	
	<li><p>Perform operations on arrays of data.</p>
</li>
	
	<li><p>Plot simple graphs from data.</p>
</li>
	
      </ul>
    </div>
  </div>

</blockquote>

<p>In this lesson we will learn how to manipulate the inflammation dataset with Python. But before we discuss how to deal with many data points, we will show how to store a single value on the computer.</p>

<p>The line below <a href="reference.html#assignment">assigns</a> the value <code class="highlighter-rouge">55</code> to a <a href="reference.html#variable">variable</a> <code class="highlighter-rouge">weight_kg</code>:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>weight_kg = 55
</code></pre>
</div>

<p>A variable is just a name for a value,
such as <code class="highlighter-rouge">x_val</code>, <code class="highlighter-rouge">current_temperature</code>, or <code class="highlighter-rouge">subject_id</code>.
Python’s variables must begin with a letter and are <a href="reference.html#case-sensitive">case sensitive</a>.
We can create a new variable by assigning a value to it using <code class="highlighter-rouge">=</code>.
When we are finished typing and press Shift+Enter,
the notebook runs our command.</p>

<p>Once a variable has a value, we can print it to the screen:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print(weight_kg)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>55
</code></pre>
</div>

<p>and do arithmetic with it:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print('weight in pounds:', 2.2 * weight_kg)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>weight in pounds: 121.0
</code></pre>
</div>

<p>As the example above shows,
we can print several things at once by separating them with commas.</p>

<p>We can also change a variable’s value by assigning it a new one:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>weight_kg = 57.5
print('weight in kilograms is now:', weight_kg)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>weight in kilograms is now: 57.5
</code></pre>
</div>

<p>If we imagine the variable as a sticky note with a name written on it,
assignment is like putting the sticky note on a particular value:</p>

<p><img src="../fig/python-sticky-note-variables-01.svg" alt="Variables as Sticky Notes" /></p>

<p>This means that assigning a value to one variable does <em>not</em> change the values of other variables.
For example,
let’s store the subject’s weight in pounds in a variable:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>weight_lb = 2.2 * weight_kg
print('weight in kilograms:', weight_kg, 'and in pounds:', weight_lb)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>weight in kilograms: 57.5 and in pounds: 126.5
</code></pre>
</div>

<p><img src="../fig/python-sticky-note-variables-02.svg" alt="Creating Another Variable" /></p>

<p>and then change <code class="highlighter-rouge">weight_kg</code>:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>weight_kg = 100.0
print('weight in kilograms is now:', weight_kg, 'and weight in pounds is still:', weight_lb)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>weight in kilograms is now: 100.0 and weight in pounds is still: 126.5
</code></pre>
</div>

<p><img src="../fig/python-sticky-note-variables-03.svg" alt="Updating a Variable" /></p>

<p>Since <code class="highlighter-rouge">weight_lb</code> doesn’t “remember” where its value came from,
it isn’t automatically updated when <code class="highlighter-rouge">weight_kg</code> changes.
This is different from the way spreadsheets work.</p>

<blockquote class="callout">
  <h2 id="whos-who-in-memory">Who’s Who in Memory</h2>

  <p>You can use the <code class="highlighter-rouge">%whos</code> command at any time to see what
variables you have created and what modules you have loaded into the computer’s memory.
As this is an IPython command, it will only work if you are in an IPython terminal or the Jupyter Notebook.</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>%whos
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>Variable    Type       Data/Info
--------------------------------
numpy       module     &lt;module 'numpy' from '/Us&lt;...&gt;kages/numpy/__init__.py'&gt;
weight_kg   float      100.0
weight_lb   float      126.5
</code></pre>
  </div>
</blockquote>

<p>Words are useful,
but what’s more useful are the sentences and stories we build with them.
Similarly,
while a lot of powerful, general tools are built into languages like Python,
specialized tools built up from these basic units live in <a href="reference.html#library">libraries</a>
that can be called upon when needed.</p>

<p>In order to load our inflammation data,
we need to access (<a href="reference.html#import">import</a> in Python terminology)
a library called <a href="http://docs.scipy.org/doc/numpy/" title="NumPy Documentation">NumPy</a>.
In general you should use this library if you want to do fancy things with numbers,
especially if you have matrices or arrays.
We can import NumPy using:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>import numpy
</code></pre>
</div>

<p>Importing a library is like getting a piece of lab equipment out of a storage locker and setting it up on the bench.
Libraries provide additional functionality to the basic Python package,
much like a new piece of equipment adds functionality to a lab space. Just like in the lab, importing too many libraries
can sometimes complicate and slow down your programs - so we only import what we need for each program. 
Once we’ve imported the library,
we can ask the library to read our data file for us:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>numpy.loadtxt(fname='inflammation-01.csv', delimiter=',')
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>array([[ 0.,  0.,  1., ...,  3.,  0.,  0.],
       [ 0.,  1.,  2., ...,  1.,  0.,  1.],
       [ 0.,  1.,  1., ...,  2.,  1.,  1.],
       ...,
       [ 0.,  1.,  1., ...,  1.,  1.,  1.],
       [ 0.,  0.,  0., ...,  0.,  2.,  0.],
       [ 0.,  0.,  1., ...,  1.,  1.,  0.]])
</code></pre>
</div>

<p>The expression <code class="highlighter-rouge">numpy.loadtxt(...)</code> is a <a href="reference.html#function-call">function call</a>
that asks Python to run the <a href="reference.html#function">function</a> <code class="highlighter-rouge">loadtxt</code> which belongs to the <code class="highlighter-rouge">numpy</code> library.
This <a href="reference.html#dotted-notation">dotted notation</a> is used everywhere in Python
to refer to the parts of things as <code class="highlighter-rouge">thing.component</code>.</p>

<p><code class="highlighter-rouge">numpy.loadtxt</code> has two <a href="reference.html#parameter">parameters</a>:
the name of the file we want to read,
and the <a href="reference.html#delimiter">delimiter</a> that separates values on a line.
These both need to be character strings (or <a href="reference.html#string">strings</a> for short),
so we put them in quotes.</p>

<p>Since we haven’t told it to do anything else with the function’s output,
the notebook displays it.
In this case,
that output is the data we just loaded.
By default,
only a few rows and columns are shown
(with <code class="highlighter-rouge">...</code> to omit elements when displaying big arrays).
To save space,
Python displays numbers as <code class="highlighter-rouge">1.</code> instead of <code class="highlighter-rouge">1.0</code>
when there’s nothing interesting after the decimal point.</p>

<p>Our call to <code class="highlighter-rouge">numpy.loadtxt</code> read our file,
but didn’t save the data in memory.
To do that,
we need to assign the array to a variable. Just as we can assign a single value to a variable, we can also assign an array of values
to a variable using the same syntax.  Let’s re-run <code class="highlighter-rouge">numpy.loadtxt</code> and save its result:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>data = numpy.loadtxt(fname='inflammation-01.csv', delimiter=',')
</code></pre>
</div>

<p>This statement doesn’t produce any output because assignment doesn’t display anything.
If we want to check that our data has been loaded,
we can print the variable’s value:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print(data)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>[[ 0.  0.  1. ...,  3.  0.  0.]
 [ 0.  1.  2. ...,  1.  0.  1.]
 [ 0.  1.  1. ...,  2.  1.  1.]
 ...,
 [ 0.  1.  1. ...,  1.  1.  1.]
 [ 0.  0.  0. ...,  0.  2.  0.]
 [ 0.  0.  1. ...,  1.  1.  0.]]
</code></pre>
</div>

<p>Now that our data is in memory,
we can start doing things with it.
First,
let’s ask what <a href="../reference/#type">type</a> of thing <code class="highlighter-rouge">data</code> refers to:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print(type(data))
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>&lt;class 'numpy.ndarray'&gt;
</code></pre>
</div>

<p>The output tells us that <code class="highlighter-rouge">data</code> currently refers to
an N-dimensional array created by the NumPy library.
These data correspond to arthritis patients’ inflammation.
The rows are the individual patients and the columns
are their daily inflammation measurements.</p>

<blockquote class="callout">
  <h2 id="data-type">Data Type</h2>

  <p>A Numpy array contains one or more elements
of the same type. <code class="highlighter-rouge">type</code> will only tell you that
a variable is a NumPy array.
We can also find out the type
of the data contained in the NumPy array.</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>print(data.dtype)
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>dtype('float64')
</code></pre>
  </div>

  <p>This tells us that the NumPy array’s elements are
<a href="../reference/#floating-point number">floating-point numbers</a>.</p>
</blockquote>

<p>With this command we can see the array’s <a href="../reference/#shape">shape</a>:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print(data.shape)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>(60, 40)
</code></pre>
</div>

<p>This tells us that <code class="highlighter-rouge">data</code> has 60 rows and 40 columns. When we created the
variable <code class="highlighter-rouge">data</code> to store our arthritis data, we didn’t just create the array, we also
created information about the array, called <a href="../reference/#member">members</a> or
attributes. This extra information describes <code class="highlighter-rouge">data</code> in
the same way an adjective describes a noun.
<code class="highlighter-rouge">data.shape</code> is an attribute  of <code class="highlighter-rouge">data</code> which describes the dimensions of <code class="highlighter-rouge">data</code>.
We use the same dotted notation for the attributes of variables
that we use for the functions in libraries
because they have the same part-and-whole relationship.</p>

<p>If we want to get a single number from the array,
we must provide an <a href="../reference/#index">index</a> in square brackets,
just as we do in math when referring to an element of a matrix.  Our inflammation data has two dimensions, so we will need to use two indices to refer to a value:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print('first value in data:', data[0, 0])
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>first value in data: 0.0
</code></pre>
</div>

<div class="python highlighter-rouge"><pre class="highlight"><code>print('middle value in data:', data[30, 20])
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>middle value in data: 13.0
</code></pre>
</div>

<p>The expression <code class="highlighter-rouge">data[30, 20]</code> may not surprise you,
but <code class="highlighter-rouge">data[0, 0]</code> might.
Programming languages like Fortran, MATLAB and R start counting at 1,
because that’s what human beings have done for thousands of years.
Languages in the C family (including C++, Java, Perl, and Python) count from 0
because it represents an offset from the first value in the array (the second
value is offset by one index from the first value). This is closer to the way
that computers represent arrays (if you are interested in the historical
reasons behind counting indices from zero, you can read
<a href="http://exple.tive.org/blarg/2013/10/22/citation-needed/">Mike Hoye’s blog post</a>).
As a result,
if we have an M×N array in Python,
its indices go from 0 to M-1 on the first axis
and 0 to N-1 on the second.
It takes a bit of getting used to,
but one way to remember the rule is that
the index is how many steps we have to take from the start to get the item we want.</p>

<p><img src="../fig/python-zero-index.png" alt="Zero Index" /></p>

<blockquote class="callout">
  <h2 id="in-the-corner">In the Corner</h2>

  <p>What may also surprise you is that when Python displays an array,
it shows the element with index <code class="highlighter-rouge">[0, 0]</code> in the upper left corner
rather than the lower left.
This is consistent with the way mathematicians draw matrices,
but different from the Cartesian coordinates.
The indices are (row, column) instead of (column, row) for the same reason,
which can be confusing when plotting data.</p>
</blockquote>

<p>An index like <code class="highlighter-rouge">[30, 20]</code> selects a single element of an array,
but we can select whole sections as well.
For example,
we can select the first ten days (columns) of values
for the first four patients (rows) like this:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print(data[0:4, 0:10])
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>[[ 0.  0.  1.  3.  1.  2.  4.  7.  8.  3.]
 [ 0.  1.  2.  1.  2.  1.  3.  2.  2.  6.]
 [ 0.  1.  1.  3.  3.  2.  6.  2.  5.  9.]
 [ 0.  0.  2.  0.  4.  2.  2.  1.  6.  7.]]
</code></pre>
</div>

<p>The <a href="../reference/#slice">slice</a> <code class="highlighter-rouge">0:4</code> means,
“Start at index 0 and go up to, but not including, index 4.”
Again,
the up-to-but-not-including takes a bit of getting used to,
but the rule is that the difference between the upper and lower bounds is the number of values in the slice.</p>

<p>We don’t have to start slices at 0:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print(data[5:10, 0:10])
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>[[ 0.  0.  1.  2.  2.  4.  2.  1.  6.  4.]
 [ 0.  0.  2.  2.  4.  2.  2.  5.  5.  8.]
 [ 0.  0.  1.  2.  3.  1.  2.  3.  5.  3.]
 [ 0.  0.  0.  3.  1.  5.  6.  5.  5.  8.]
 [ 0.  1.  1.  2.  1.  3.  5.  3.  5.  8.]]
</code></pre>
</div>

<p>We also don’t have to include the upper and lower bound on the slice.
If we don’t include the lower bound,
Python uses 0 by default;
if we don’t include the upper,
the slice runs to the end of the axis,
and if we don’t include either
(i.e., if we just use ‘:’ on its own),
the slice includes everything:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>small = data[:3, 36:]
print('small is:')
print(small)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>small is:
[[ 2.  3.  0.  0.]
 [ 1.  1.  0.  1.]
 [ 2.  2.  1.  1.]]
</code></pre>
</div>

<p>Arrays also know how to perform common mathematical operations on their values.
The simplest operations with data are arithmetic:
add, subtract, multiply, and divide.
 When you do such operations on arrays,
the operation is done on each individual element of the array.
Thus:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>doubledata = data * 2.0
</code></pre>
</div>

<p>will create a new array <code class="highlighter-rouge">doubledata</code>
whose elements have the value of two times the value of the corresponding elements in <code class="highlighter-rouge">data</code>:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print('original:')
print(data[:3, 36:])
print('doubledata:')
print(doubledata[:3, 36:])
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>original:
[[ 2.  3.  0.  0.]
 [ 1.  1.  0.  1.]
 [ 2.  2.  1.  1.]]
doubledata:
[[ 4.  6.  0.  0.]
 [ 2.  2.  0.  2.]
 [ 4.  4.  2.  2.]]
</code></pre>
</div>

<p>If,
instead of taking an array and doing arithmetic with a single value (as above)
you did the arithmetic operation with another array of the same shape,
the operation will be done on corresponding elements of the two arrays.
Thus:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>tripledata = doubledata + data
</code></pre>
</div>

<p>will give you an array where <code class="highlighter-rouge">tripledata[0,0]</code> will equal <code class="highlighter-rouge">doubledata[0,0]</code> plus <code class="highlighter-rouge">data[0,0]</code>,
and so on for all other elements of the arrays.</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print('tripledata:')
print(tripledata[:3, 36:])
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>tripledata:
[[ 6.  9.  0.  0.]
 [ 3.  3.  0.  3.]
 [ 6.  6.  3.  3.]]
</code></pre>
</div>

<p>Often, we want to do more than add, subtract, multiply, and divide values of data.
NumPy knows how to do more complex operations on arrays.
If we want to find the average inflammation for all patients on all days,
for example,
we can ask NumPy to compute <code class="highlighter-rouge">data</code>’s mean value:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print(numpy.mean(data))
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>6.14875
</code></pre>
</div>

<p><code class="highlighter-rouge">mean</code> is a <a href="../reference/#function">function</a> that takes
an array as an <a href="../reference/#argument">argument</a>.
If variables are nouns, functions are verbs:
they do things with variables.</p>

<blockquote class="callout">
  <h2 id="not-all-functions-have-input">Not All Functions Have Input</h2>

  <p>Generally, a function uses inputs to produce outputs.
However, some functions produce outputs without
needing any input. For example, checking the current time
doesn’t require any input.</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>import time
print(time.ctime())
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>'Sat Mar 26 13:07:33 2016'
</code></pre>
  </div>

  <p>For functions that don’t take in any arguments,
we still need parentheses (<code class="highlighter-rouge">()</code>)
to tell Python to go and do something for us.</p>
</blockquote>

<p>NumPy has lots of useful functions that take an array as input.
Let’s use three of those functions to get some descriptive values about the dataset.
We’ll also use multiple assignment,
a convenient Python feature that will enable us to do this all in one line.</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>maxval, minval, stdval = numpy.max(data), numpy.min(data), numpy.std(data)

print('maximum inflammation:', maxval)
print('minimum inflammation:', minval)
print('standard deviation:', stdval)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>maximum inflammation: 20.0
minimum inflammation: 0.0
standard deviation: 4.61383319712
</code></pre>
</div>

<blockquote class="callout">
  <h2 id="mystery-functions-in-ipython">Mystery Functions in IPython</h2>

  <p>How did we know what functions NumPy has and how to use them?
If you are working in the IPython/Jupyter Notebook there is an easy way to find out.
If you type the name of something followed by a dot, then you can use tab completion
(e.g. type <code class="highlighter-rouge">numpy.</code> and then press tab)
to see a list of all functions and attributes that you can use. After selecting one you
can also add a question mark (e.g. <code class="highlighter-rouge">numpy.cumprod?</code>) and IPython will return an
explanation of the method! This is the same as doing <code class="highlighter-rouge">help(numpy.cumprod)</code>.</p>
</blockquote>

<p>When analyzing data, though,
we often want to look at partial statistics,
such as the maximum value per patient
or the average value per day.
One way to do this is to create a new temporary array of the data we want,
then ask it to do the calculation:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>patient_0 = data[0, :] # 0 on the first axis (rows), everything on the second (columns)
print('maximum inflammation for patient 0:', patient_0.max())
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>maximum inflammation for patient 0: 18.0
</code></pre>
</div>

<p>Everything in a line of code following the ‘#’ symbol is a
<a href="../reference/#comment">comment</a> that is ignored by Python.
Comments allow programmers to leave explanatory notes for other
programmers or their future selves.</p>

<p>We don’t actually need to store the row in a variable of its own.
Instead, we can combine the selection and the function call:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print('maximum inflammation for patient 2:', numpy.max(data[2, :]))
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>maximum inflammation for patient 2: 19.0
</code></pre>
</div>

<p>What if we need the maximum inflammation for each patient over all days (as in the
next diagram on the left), or the average for each day (as in the
diagram on the right)? As the diagram below shows, we want to perform the
operation across an axis:</p>

<p><img src="../fig/python-operations-across-axes.png" alt="Operations Across Axes" /></p>

<p>To support this,
most array functions allow us to specify the axis we want to work on.
If we ask for the average across axis 0 (rows in our 2D example),
we get:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print(numpy.mean(data, axis=0))
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>[  0.           0.45         1.11666667   1.75         2.43333333   3.15
   3.8          3.88333333   5.23333333   5.51666667   5.95         5.9
   8.35         7.73333333   8.36666667   9.5          9.58333333
  10.63333333  11.56666667  12.35        13.25        11.96666667
  11.03333333  10.16666667  10.           8.66666667   9.15         7.25
   7.33333333   6.58333333   6.06666667   5.95         5.11666667   3.6
   3.3          3.56666667   2.48333333   1.5          1.13333333
   0.56666667]
</code></pre>
</div>

<p>As a quick check,
we can ask this array what its shape is:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print(numpy.mean(data, axis=0).shape)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>(40,)
</code></pre>
</div>

<p>The expression <code class="highlighter-rouge">(40,)</code> tells us we have an N×1 vector,
so this is the average inflammation per day for all patients.
If we average across axis 1 (columns in our 2D example), we get:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print(numpy.mean(data, axis=1))
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>[ 5.45   5.425  6.1    5.9    5.55   6.225  5.975  6.65   6.625  6.525
  6.775  5.8    6.225  5.75   5.225  6.3    6.55   5.7    5.85   6.55
  5.775  5.825  6.175  6.1    5.8    6.425  6.05   6.025  6.175  6.55
  6.175  6.35   6.725  6.125  7.075  5.725  5.925  6.15   6.075  5.75
  5.975  5.725  6.3    5.9    6.75   5.925  7.225  6.15   5.95   6.275  5.7
  6.1    6.825  5.975  6.725  5.7    6.25   6.4    7.05   5.9  ]
</code></pre>
</div>

<p>which is the average inflammation per patient across all days.</p>

<p>The mathematician Richard Hamming once said,
“The purpose of computing is insight, not numbers,”
and the best way to develop insight is often to visualize data.
Visualization deserves an entire lecture (of course) of its own,
but we can explore a few features of Python’s <code class="highlighter-rouge">matplotlib</code> library here.
While there is no “official” plotting library,
this package is the de facto standard.
First,
we will import the <code class="highlighter-rouge">pyplot</code> module from <code class="highlighter-rouge">matplotlib</code>
and use two of its functions to create and display a heat map of our data:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>import matplotlib.pyplot
image = matplotlib.pyplot.imshow(data)
matplotlib.pyplot.show()
</code></pre>
</div>

<p><img src="../fig/01-numpy_71_0.png" alt="Heatmap of the Data" /></p>

<p>Blue regions in this heat map are low values, while red shows high values.
As we can see,
inflammation rises and falls over a 40-day period.</p>

<blockquote class="callout">
  <h2 id="some-ipython-magic">Some IPython Magic</h2>

  <p>If you’re using an IPython / Jupyter notebook,
you’ll need to execute the following command
in order for your matplotlib images to appear
in the notebook when <code class="highlighter-rouge">show()</code> is called:</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>%matplotlib inline
</code></pre>
  </div>

  <p>The <code class="highlighter-rouge">%</code> indicates an IPython magic function -
a function that is only valid within the notebook environment.
Note that you only have to execute this function once per notebook.</p>
</blockquote>

<p>Let’s take a look at the average inflammation over time:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>ave_inflammation = numpy.mean(data, axis=0)
ave_plot = matplotlib.pyplot.plot(ave_inflammation)
matplotlib.pyplot.show()
</code></pre>
</div>

<p><img src="../fig/01-numpy_73_0.png" alt="Average Inflammation Over Time" /></p>

<p>Here,
we have put the average per day across all patients in the variable <code class="highlighter-rouge">ave_inflammation</code>,
then asked <code class="highlighter-rouge">matplotlib.pyplot</code> to create and display a line graph of those values.
The result is roughly a linear rise and fall,
which is suspicious:
based on other studies,
we expect a sharper rise and slower fall.
Let’s have a look at two other statistics:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>max_plot = matplotlib.pyplot.plot(numpy.max(data, axis=0))
matplotlib.pyplot.show()
</code></pre>
</div>

<p><img src="../fig/01-numpy_75_1.png" alt="Maximum Value Along The First Axis" /></p>

<div class="python highlighter-rouge"><pre class="highlight"><code>min_plot = matplotlib.pyplot.plot(numpy.min(data, axis=0))
matplotlib.pyplot.show()
</code></pre>
</div>

<p><img src="../fig/01-numpy_75_3.png" alt="Minimum Value Along The First Axis" /></p>

<p>The maximum value rises and falls perfectly smoothly,
while the minimum seems to be a step function.
Neither result seems particularly likely,
so either there’s a mistake in our calculations
or something is wrong with our data.
This insight would have been difficult to reach by
examining the data without visualization tools.</p>

<p>You can group similar plots in a single figure using subplots.
This script below uses a number of new commands. The function <code class="highlighter-rouge">matplotlib.pyplot.figure()</code>
creates a space into which we will place all of our plots. The parameter <code class="highlighter-rouge">figsize</code>
tells Python how big to make this space. Each subplot is placed into the figure using
its <code class="highlighter-rouge">add_subplot</code> <a href="../reference/#method">method</a>. The <code class="highlighter-rouge">add_subplot</code> method takes 3 parameters. The first denotes
how many total rows of subplots there are, the second parameter refers to the
total number of subplot columns, and the final parameter denotes which subplot
your variable is referencing (left-to-right, top-to-bottom). Each subplot is stored in a
different variable (<code class="highlighter-rouge">axes1</code>, <code class="highlighter-rouge">axes2</code>, <code class="highlighter-rouge">axes3</code>). Once a subplot is created, the axes can
be titled using the <code class="highlighter-rouge">set_xlabel()</code> command (or <code class="highlighter-rouge">set_ylabel()</code>).
Here are our three plots side by side:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>import numpy
import matplotlib.pyplot

data = numpy.loadtxt(fname='inflammation-01.csv', delimiter=',')

fig = matplotlib.pyplot.figure(figsize=(10.0, 3.0))

axes1 = fig.add_subplot(1, 3, 1)
axes2 = fig.add_subplot(1, 3, 2)
axes3 = fig.add_subplot(1, 3, 3)

axes1.set_ylabel('average')
axes1.plot(numpy.mean(data, axis=0))

axes2.set_ylabel('max')
axes2.plot(numpy.max(data, axis=0))

axes3.set_ylabel('min')
axes3.plot(numpy.min(data, axis=0))

fig.tight_layout()

matplotlib.pyplot.show()
</code></pre>
</div>

<p><img src="../fig/01-numpy_80_0.png" alt="The Previous Plots as Subplots" /></p>

<p>The <a href="../reference/#function-call">call</a> to <code class="highlighter-rouge">loadtxt</code> reads our data,
and the rest of the program tells the plotting library
how large we want the figure to be,
that we’re creating three subplots,
what to draw for each one,
and that we want a tight layout.
(Perversely,
if we leave out that call to <code class="highlighter-rouge">fig.tight_layout()</code>,
the graphs will actually be squeezed together more closely.)</p>

<blockquote class="callout">
  <h2 id="scientists-dislike-typing">Scientists Dislike Typing</h2>

  <p>We will always use the syntax <code class="highlighter-rouge">import numpy</code> to import NumPy.
However, in order to save typing, it is
<a href="http://www.scipy.org/getting-started.html#an-example-script">often suggested</a>
to make a shortcut like so: <code class="highlighter-rouge">import numpy as np</code>.
If you ever see Python code online using a NumPy function with <code class="highlighter-rouge">np</code>
(for example, <code class="highlighter-rouge">np.loadtxt(...)</code>), it’s because they’ve used this shortcut.
When working with other people, it is important to agree on a convention of how common libraries are imported.</p>
</blockquote>
<blockquote class="challenge">
  <h2 id="check-your-understanding">Check Your Understanding</h2>

  <p>Draw diagrams showing what variables refer to what values after each statement in the following program:</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>mass = 47.5
age = 122
mass = mass * 2.0
age = age - 20
</code></pre>
  </div>
</blockquote>

<blockquote class="challenge">
  <h2 id="sorting-out-references">Sorting Out References</h2>

  <p>What does the following program print out?</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>first, second = 'Grace', 'Hopper'
third, fourth = second, first
print(third, fourth)
</code></pre>
  </div>

  <blockquote class="solution">
    <h2 id="solution">Solution</h2>
    <div class="output highlighter-rouge"><pre class="highlight"><code>Hopper Grace
</code></pre>
    </div>
  </blockquote>
</blockquote>

<blockquote class="challenge">
  <h2 id="slicing-strings">Slicing Strings</h2>

  <p>A section of an array is called a <a href="../reference/#slice">slice</a>.
We can take slices of character strings as well:</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>element = 'oxygen'
print('first three characters:', element[0:3])
print('last three characters:', element[3:6])
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>first three characters: oxy
last three characters: gen
</code></pre>
  </div>

  <p>What is the value of <code class="highlighter-rouge">element[:4]</code>?
What about <code class="highlighter-rouge">element[4:]</code>?
Or <code class="highlighter-rouge">element[:]</code>?</p>

  <blockquote class="solution">
    <h2 id="solution-1">Solution</h2>
    <div class="output highlighter-rouge"><pre class="highlight"><code>oxyg
en
oxygen
</code></pre>
    </div>
  </blockquote>

  <p>What is <code class="highlighter-rouge">element[-1]</code>?
What is <code class="highlighter-rouge">element[-2]</code>?</p>

  <blockquote class="solution">
    <h2 id="solution-2">Solution</h2>
    <div class="output highlighter-rouge"><pre class="highlight"><code>n
e
</code></pre>
    </div>
  </blockquote>

  <p>Given those answers,
explain what <code class="highlighter-rouge">element[1:-1]</code> does.</p>

  <blockquote class="solution">
    <h2 id="solution-3">Solution</h2>
    <p>Creates a substring from index 1 up to (not including) the final index,
effectively removing the first and last letters from ‘oxygen’</p>
  </blockquote>
</blockquote>

<blockquote class="challenge">
  <h2 id="thin-slices">Thin Slices</h2>

  <p>The expression <code class="highlighter-rouge">element[3:3]</code> produces an <a href="../reference/#empty-string">empty string</a>,
i.e., a string that contains no characters.
If <code class="highlighter-rouge">data</code> holds our array of patient data,
what does <code class="highlighter-rouge">data[3:3, 4:4]</code> produce?
What about <code class="highlighter-rouge">data[3:3, :]</code>?</p>

  <blockquote class="solution">
    <h2 id="solution-4">Solution</h2>
    <div class="output highlighter-rouge"><pre class="highlight"><code>[]
[]
</code></pre>
    </div>
  </blockquote>
</blockquote>

<blockquote class="challenge">
  <h2 id="plot-scaling">Plot Scaling</h2>

  <p>Why do all of our plots stop just short of the upper end of our graph?</p>

  <blockquote class="solution">
    <h2 id="solution-5">Solution</h2>
    <p>Because matplotlib normally sets x and y axes limits to the min and max of our data
(depending on data range)</p>
  </blockquote>

  <p>If we want to change this, we can use the <code class="highlighter-rouge">set_ylim(min, max)</code> method of each ‘axes’,
for example:</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>axes3.set_ylim(0,6)
</code></pre>
  </div>

  <p>Update your plotting code to automatically set a more appropriate scale.
(Hint: you can make use of the <code class="highlighter-rouge">max</code> and <code class="highlighter-rouge">min</code> methods to help.)</p>

  <blockquote class="solution">
    <h2 id="solution-6">Solution</h2>
    <div class="python highlighter-rouge"><pre class="highlight"><code># One method
axes3.set_ylabel('min')
axes3.plot(numpy.min(data, axis=0))
axes3.set_ylim(0,6)
</code></pre>
    </div>
  </blockquote>

  <blockquote class="solution">
    <h2 id="solution-7">Solution</h2>
    <div class="python highlighter-rouge"><pre class="highlight"><code># A more automated approach
min_data = numpy.min(data, axis=0)
axes3.set_ylabel('min')
axes3.plot(min_data)
axes3.set_ylim(numpy.min(min_data), numpy.max(min_data) * 1.1)
</code></pre>
    </div>
  </blockquote>
</blockquote>

<blockquote class="challenge">
  <h2 id="drawing-straight-lines">Drawing Straight Lines</h2>

  <p>In the center and right subplots above, we  expect all lines to look like step functions, because
non-integer value are not realistic for the minimum and maximum values. However, you can see
that the lines are not always vertical or horizontal, and in particular the step function
in the subplot on the right looks slanted. Why is this?</p>

  <blockquote class="solution">
    <h2 id="solution-8">Solution</h2>
    <p>Because matplotlib interpolates (draws a straight line) between the points.
One way to do avoid this is to use the Matplotlib <code class="highlighter-rouge">drawstyle</code> option:</p>

    <div class="python highlighter-rouge"><pre class="highlight"><code>import numpy
import matplotlib.pyplot

data = numpy.loadtxt(fname='inflammation-01.csv', delimiter=',')

fig = matplotlib.pyplot.figure(figsize=(10.0, 3.0))

axes1 = fig.add_subplot(1, 3, 1)
axes2 = fig.add_subplot(1, 3, 2)
axes3 = fig.add_subplot(1, 3, 3)

axes1.set_ylabel('average')
axes1.plot(numpy.mean(data, axis=0), drawstyle='steps-mid')

axes2.set_ylabel('max')
axes2.plot(numpy.max(data, axis=0), drawstyle='steps-mid')

axes3.set_ylabel('min')
axes3.plot(numpy.min(data, axis=0), drawstyle='steps-mid')

fig.tight_layout()

matplotlib.pyplot.show()
</code></pre>
    </div>
    <p><img src="../fig/01-numpy_exercise_0.png" alt="Plot with step lines" /></p>
  </blockquote>
</blockquote>

<blockquote class="challenge">
  <h2 id="make-your-own-plot">Make Your Own Plot</h2>

  <p>Create a plot showing the standard deviation (<code class="highlighter-rouge">numpy.std</code>)
of the inflammation data for each day across all patients.</p>

  <blockquote class="solution">
    <h2 id="solution-9">Solution</h2>
    <div class="python highlighter-rouge"><pre class="highlight"><code>max_plot = matplotlib.pyplot.plot(numpy.std(data, axis=0))
matplotlib.pyplot.show()
</code></pre>
    </div>
  </blockquote>
</blockquote>

<blockquote class="challenge">
  <h2 id="moving-plots-around">Moving Plots Around</h2>

  <p>Modify the program to display the three plots on top of one another
instead of side by side.</p>

  <blockquote class="solution">
    <h2 id="solution-10">Solution</h2>
    <div class="python highlighter-rouge"><pre class="highlight"><code>import numpy
import matplotlib.pyplot

data = numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',')

# change figsize (swap width and height)
fig = matplotlib.pyplot.figure(figsize=(3.0, 10.0))

# change add_subplot (swap first two parameters)
axes1 = fig.add_subplot(3, 1, 1)
axes2 = fig.add_subplot(3, 1, 2)
axes3 = fig.add_subplot(3, 1, 3)

axes1.set_ylabel('average')
axes1.plot(numpy.mean(data, axis=0))

axes2.set_ylabel('max')
axes2.plot(numpy.max(data, axis=0))

axes3.set_ylabel('min')
axes3.plot(numpy.min(data, axis=0))

fig.tight_layout()

matplotlib.pyplot.show()
</code></pre>
    </div>
  </blockquote>
</blockquote>

<blockquote class="challenge">
  <h2 id="stacking-arrays">Stacking Arrays</h2>

  <p>Arrays can be concatenated and stacked on top of one another,
using NumPy’s <code class="highlighter-rouge">vstack</code> and <code class="highlighter-rouge">hstack</code> functions for vertical and horizontal stacking, respectively.</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>import numpy

A = numpy.array([[1,2,3], [4,5,6], [7, 8, 9]])
print('A = ')
print(A)

B = numpy.hstack([A, A])
print('B = ')
print(B)

C = numpy.vstack([A, A])
print('C = ')
print(C)
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>A =
[[1 2 3]
 [4 5 6]
 [7 8 9]]
B =
[[1 2 3 1 2 3]
 [4 5 6 4 5 6]
 [7 8 9 7 8 9]]
C =
[[1 2 3]
 [4 5 6]
 [7 8 9]
 [1 2 3]
 [4 5 6]
 [7 8 9]]
</code></pre>
  </div>

  <p>Write some additional code that slices the first and last columns of <code class="highlighter-rouge">A</code>,
and stacks them into a 3x2 array.
Make sure to <code class="highlighter-rouge">print</code> the results to verify your solution.</p>

  <blockquote class="solution">
    <h2 id="solution-11">Solution</h2>

    <p>A ‘gotcha’ with array indexing is that singleton dimensions
are dropped by default. That means <code class="highlighter-rouge">A[:, 0]</code> is a one dimensional
array, which won’t stack as desired. To preserve singleton dimensions,
the index itself can be a slice or array. For example, <code class="highlighter-rouge">A[:, :1]</code> returns
a two dimensional array with one singleton dimension (i.e. a column
vector).</p>

    <div class="python highlighter-rouge"><pre class="highlight"><code>D = numpy.hstack((A[:, :1], A[:, -1:]))
print('D = ')
print(D)
</code></pre>
    </div>

    <div class="output highlighter-rouge"><pre class="highlight"><code>D =
[[1 3]
 [4 6]
 [7 9]]
</code></pre>
    </div>
  </blockquote>

  <blockquote class="solution">
    <h2 id="solution-12">Solution</h2>

    <p>An alternative way to achieve the same result is to use Numpy’s
delete function to remove the second column of A.</p>

    <div class="python highlighter-rouge"><pre class="highlight"><code>D = numpy.delete(A, 1, 1)
print('D = ')
print(D)
</code></pre>
    </div>

    <div class="output highlighter-rouge"><pre class="highlight"><code>D =
[[1 3]
 [4 6]
 [7 9]]
</code></pre>
    </div>
  </blockquote>
</blockquote>

<blockquote class="challenge">
  <h2 id="change-in-inflammation">Change In Inflammation</h2>

  <p>This patient data is <em>longitudinal</em> in the sense that each row represents a
series of observations relating to one individual. This means that change
inflammation is a meaningful concept.</p>

  <p>The <code class="highlighter-rouge">numpy.diff()</code> function takes a NumPy array and returns the 
difference along a specified axis.</p>

  <p>Which axis would it make sense to use this function along?</p>

  <blockquote class="solution">
    <h2 id="solution-13">Solution</h2>
    <p>Since the row axis (0) is patients, it does not make sense to get the
difference between two arbitrary patients. The column axis (1) is in
days, so the differnce is the change in inflammation – a meaningful
concept.</p>

    <div class="python highlighter-rouge"><pre class="highlight"><code>numpy.diff(data, axis=1)
</code></pre>
    </div>
  </blockquote>

  <p>If the shape of an individual data file is <code class="highlighter-rouge">(60, 40)</code> (60 rows and 40
columns), what would the shape of the array be after you run the <code class="highlighter-rouge">diff()</code>
function and why?</p>

  <blockquote class="solution">
    <h2 id="solution-14">Solution</h2>
    <p>The shape will be <code class="highlighter-rouge">(60, 39)</code> because there is one fewer difference between
columns than there are columns in the data.</p>
  </blockquote>

  <p>How would you find the largest change in inflammation for each patient? Does
it matter if the change in inflammation is an increase or a decrease?</p>

  <blockquote class="solution">
    <h2 id="solution-15">Solution</h2>
    <p>By using the <code class="highlighter-rouge">numpy.max()</code> function after you apply the <code class="highlighter-rouge">numpy.diff()</code>
function, you will get the largest difference between days.</p>

    <div class="python highlighter-rouge"><pre class="highlight"><code>numpy.max(numpy.diff(data, axis=1), axis=1)
</code></pre>
    </div>

    <div class="python highlighter-rouge"><pre class="highlight"><code>array([  7.,  12.,  11.,  10.,  11.,  13.,  10.,   8.,  10.,  10.,   7.,
         7.,  13.,   7.,  10.,  10.,   8.,  10.,   9.,  10.,  13.,   7.,
        12.,   9.,  12.,  11.,  10.,  10.,   7.,  10.,  11.,  10.,   8.,
        11.,  12.,  10.,   9.,  10.,  13.,  10.,   7.,   7.,  10.,  13.,
        12.,   8.,   8.,  10.,  10.,   9.,   8.,  13.,  10.,   7.,  10.,
         8.,  12.,  10.,   7.,  12.])
</code></pre>
    </div>

    <p>If a difference is a <em>decrease</em>, then the difference will be negative. If
you are interested in the <strong>magnitude</strong> of the change and not just the
direction, the <code class="highlighter-rouge">numpy.absolute()</code> function will provide that.</p>

    <p>Notice the difference if you get the largest <em>absolute</em> difference
between readings.</p>

    <div class="python highlighter-rouge"><pre class="highlight"><code>numpy.max(numpy.absolute(numpy.diff(data, axis=1)), axis=1)
</code></pre>
    </div>

    <div class="python highlighter-rouge"><pre class="highlight"><code>array([ 12.,  14.,  11.,  13.,  11.,  13.,  10.,  12.,  10.,  10.,  10.,
        12.,  13.,  10.,  11.,  10.,  12.,  13.,   9.,  10.,  13.,   9.,
        12.,   9.,  12.,  11.,  10.,  13.,   9.,  13.,  11.,  11.,   8.,
        11.,  12.,  13.,   9.,  10.,  13.,  11.,  11.,  13.,  11.,  13.,
        13.,  10.,   9.,  10.,  10.,   9.,   9.,  13.,  10.,   9.,  10.,
        11.,  13.,  10.,  10.,  12.])
</code></pre>
    </div>

  </blockquote>
</blockquote>


<blockquote class="keypoints">
  <h2>Key Points</h2>
  <ul>
    
    <li><p>Import a library into a program using <code class="highlighter-rouge">import libraryname</code>.</p>
</li>
    
    <li><p>Use the <code class="highlighter-rouge">numpy</code> library to work with arrays in Python.</p>
</li>
    
    <li><p>Use <code class="highlighter-rouge">variable = value</code> to assign a value to a variable in order to record it in memory.</p>
</li>
    
    <li><p>Variables are created on demand whenever a value is assigned to them.</p>
</li>
    
    <li><p>Use <code class="highlighter-rouge">print(something)</code> to display the value of <code class="highlighter-rouge">something</code>.</p>
</li>
    
    <li><p>The expression <code class="highlighter-rouge">array.shape</code> gives the shape of an array.</p>
</li>
    
    <li><p>Use <code class="highlighter-rouge">array[x, y]</code> to select a single element from a 2D array.</p>
</li>
    
    <li><p>Array indices start at 0, not 1.</p>
</li>
    
    <li><p>Use <code class="highlighter-rouge">low:high</code> to specify a <code class="highlighter-rouge">slice</code> that includes the indices from <code class="highlighter-rouge">low</code> to <code class="highlighter-rouge">high-1</code>.</p>
</li>
    
    <li><p>All the indexing and slicing that works on arrays also works on strings.</p>
</li>
    
    <li><p>Use <code class="highlighter-rouge"># some kind of explanation</code> to add comments to programs.</p>
</li>
    
    <li><p>Use <code class="highlighter-rouge">numpy.mean(array)</code>, <code class="highlighter-rouge">numpy.max(array)</code>, and <code class="highlighter-rouge">numpy.min(array)</code> to calculate simple statistics.</p>
</li>
    
    <li><p>Use <code class="highlighter-rouge">numpy.mean(array, axis=0)</code> or <code class="highlighter-rouge">numpy.mean(array, axis=1)</code> to calculate statistics across the specified axis.</p>
</li>
    
    <li><p>Use the <code class="highlighter-rouge">pyplot</code> library from <code class="highlighter-rouge">matplotlib</code> for creating simple visualizations.</p>
</li>
    
  </ul>
</blockquote>

</article>

<div class="row">
  <div class="col-md-1">
    <h3>
      
      <a href="../"><span class="glyphicon glyphicon-menu-up" aria-hidden="true"></span><span class="sr-only">lesson home</span></a>
      
    </h3>
  </div>
  <div class="col-md-10">
    
  </div>
  <div class="col-md-1">
    <h3>
      
      <a href="../02-loop/"><span class="glyphicon glyphicon-menu-right" aria-hidden="true"></span><span class="sr-only">next episode</span></a>
      
    </h3>
  </div>
</div>


      
      
<footer>
  <div class="row">
    <div class="col-md-6" align="left">
      <h4>
	Copyright &copy; 2016–2017
	
	<a href="https://software-carpentry.org">Software Carpentry Foundation</a>
	
      </h4>
    </div>
    <div class="col-md-6" align="right">
      <h4>
	
	<a href="/edit/gh-pages/_episodes/01-numpy.md">Edit on GitHub</a>
	
	/
	<a href="/blob/gh-pages/CONTRIBUTING.md">Contributing</a>
	/
	<a href="/">Source</a>
	/
	<a href="/blob/gh-pages/CITATION">Cite</a>
	/
	<a href="">Contact</a>
      </h4>
    </div>
  </div>
</footer>

      
    </div>
    
<script src="../assets/js/jquery.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="../assets/js/lesson.js"></script>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-37305346-2', 'auto');
  ga('send', 'pageview');
</script>

  </body>
</html>