05-PandasWeather.ipynb 218 KB
Newer Older
Simon Clarke's avatar
Simon Clarke 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
26
27
28
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## A Practical Introduction to Pandas "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Pandas is one of the main Python packages for dealing with data. It is used widely in Data Science, and provides many tools for the manipulation and investigation of data sets. This tutorial introduces the basic concept of Pandas and applies these to weather data for Melbourne Airport from the Bureau of Meteorology."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Contents"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* Introduction\n",
Simon Clarke's avatar
Simon Clarke committed
29
    "* Melbourne Weather Data (Combining Pandas and Plotting)\n",
Simon Clarke's avatar
Simon Clarke committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
    "* Exercises"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Before applying Pandas to the Melbourne weather data, we will introduce some basic concepts. \n",
    "\n",
    "First we import the necessary libraries. The convention for Pandas is to use the abbreviation `pd`."
   ]
  },
  {
   "cell_type": "code",
51
   "execution_count": 2,
Simon Clarke's avatar
Simon Clarke committed
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
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Series"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Pandas series can be thought of as generalizations of one-dimensional arrays or of dictionaries. In their simplest form they are an array with an explicit numerical index.\n",
    "\n",
    "To create a series we use the function `pd.Series()` and pass the argument as an array."
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
78
   "execution_count": 2,
Simon Clarke's avatar
Simon Clarke committed
79
80
81
82
83
84
85
86
87
88
89
90
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    5\n",
       "1    6\n",
       "2    7\n",
       "3    8\n",
       "dtype: int64"
      ]
     },
Simon Clarke's avatar
Simon Clarke committed
91
     "execution_count": 2,
Simon Clarke's avatar
Simon Clarke committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = pd.Series([5, 6, 7, 8])\n",
    "data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The series now has two objects we can view: the values for the series and the corresponding indices."
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
110
   "execution_count": 3,
Simon Clarke's avatar
Simon Clarke committed
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
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Series values: [5 6 7 8]\n",
      "Series indices: RangeIndex(start=0, stop=4, step=1)\n"
     ]
    }
   ],
   "source": [
    "print('Series values:',data.values)\n",
    "print('Series indices:',data.index)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can now access the data in the same way we would for a `numpy` array, except that we also get information about the indices."
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
136
   "execution_count": 4,
Simon Clarke's avatar
Simon Clarke committed
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
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Second element of series is: 6\n",
      "Second and third elements of series are:\n",
      "1    6\n",
      "2    7\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "print('Second element of series is:',data[1])\n",
    "print('Second and third elements of series are:')\n",
    "print(data[1:3])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The indices for the series are no longer limited to being integers. For example, by specifying the argument `index`, we can make the indices a series of strings."
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
166
   "execution_count": 5,
Simon Clarke's avatar
Simon Clarke committed
167
168
169
170
171
172
173
174
175
176
177
178
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "alpha    5\n",
       "beta     6\n",
       "gamma    7\n",
       "delta    8\n",
       "dtype: int64"
      ]
     },
Simon Clarke's avatar
Simon Clarke committed
179
     "execution_count": 5,
Simon Clarke's avatar
Simon Clarke committed
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = pd.Series([5, 6, 7, 8], index=['alpha','beta','gamma','delta'])\n",
    "data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now the data can be referred to by our new indices. Notice that using a slice of these indices the last element is included, compared to when we used integer indices and the last element is not included. "
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
198
   "execution_count": 6,
Simon Clarke's avatar
Simon Clarke committed
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
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Single element: 5\n",
      "Slice of elements:\n",
      "alpha    5\n",
      "beta     6\n",
      "gamma    7\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "print('Single element:',data['alpha'])\n",
    "print('Slice of elements:')\n",
    "print(data['alpha':'gamma'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The series can now be sorted using the method `s.sort_values()` (here `s` represents the name of the current series). To sort our series in descending order, we can therefore use:"
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
229
   "execution_count": 7,
Simon Clarke's avatar
Simon Clarke committed
230
231
232
233
234
235
236
237
238
239
240
241
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "delta    8\n",
       "gamma    7\n",
       "beta     6\n",
       "alpha    5\n",
       "dtype: int64"
      ]
     },
Simon Clarke's avatar
Simon Clarke committed
242
     "execution_count": 7,
Simon Clarke's avatar
Simon Clarke committed
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data.sort_values(ascending=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We also filter the results using a `mask`. For example, if we want all values in the series equal to 6, we use:"
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
260
   "execution_count": 8,
Simon Clarke's avatar
Simon Clarke committed
261
262
263
264
265
266
267
268
269
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "beta    6\n",
       "dtype: int64"
      ]
     },
Simon Clarke's avatar
Simon Clarke committed
270
     "execution_count": 8,
Simon Clarke's avatar
Simon Clarke committed
271
272
273
274
275
276
277
278
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data[data == 6]"
   ]
  },
279
280
281
282
283
284
285
286
287
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The mask is itself a series with booleans as values instead of the original values that can be used to subset the orginal series."
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
288
   "execution_count": 9,
289
290
291
292
293
294
295
296
297
298
299
300
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "alpha    False\n",
       "beta      True\n",
       "gamma    False\n",
       "delta    False\n",
       "dtype: bool"
      ]
     },
Simon Clarke's avatar
Simon Clarke committed
301
     "execution_count": 9,
302
303
304
305
306
307
308
309
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data == 6"
   ]
  },
Simon Clarke's avatar
Simon Clarke committed
310
311
312
313
314
315
316
317
318
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Masks can have multiple criteria, which are separated by an `&` (and) to specify both criteria must be true, or `!` (or) to specify either criteria to be true. Each of these criteria needs to be surrounded by brackets. To find all elements in the series greater than or equal to 5 and less than 7, we can write:"
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
319
   "execution_count": 10,
Simon Clarke's avatar
Simon Clarke committed
320
321
322
323
324
325
326
327
328
329
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "alpha    5\n",
       "beta     6\n",
       "dtype: int64"
      ]
     },
Simon Clarke's avatar
Simon Clarke committed
330
     "execution_count": 10,
Simon Clarke's avatar
Simon Clarke committed
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
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data[(data >= 5) & (data < 7)]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### DataFrames"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "DataFrames are two-dimensional versions of series, which can have row indices and column names. The columns can be different datatypes, e.g., integers, floats, strings or Boolean. Generally, dataframes are used much more than series, and can be thought of as analogous to an Excel worksheet or database table. \n",
    "\n",
    "There are a number of ways to create dataframes, we will just cover two here. The first is to create the dataframe from a sequence of series. Below we define three series corresponding to properties of the states and territories of Australia. Notice that for the last series the indices are ordered differently from the first two series."
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
357
   "execution_count": 11,
Simon Clarke's avatar
Simon Clarke committed
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
   "metadata": {},
   "outputs": [],
   "source": [
    "area = pd.Series([2523924, 1723030, 1334404, 979651, 801137, 227038, 64519, 2358], \n",
    "                 index=['WA', 'QLD', 'NT', 'SA', 'NSW', 'VIC', 'TAS', 'ACT'])\n",
    "population = pd.Series([2667130, 5184847, 246500, 1770591, 8166369, 6680648, 541071, 431215], \n",
    "                 index=['WA', 'QLD', 'NT', 'SA', 'NSW', 'VIC', 'TAS', 'ACT'])\n",
    "capitals = pd.Series(['Sydney', 'Melbourne', 'Brisbane', 'Adelaide', 'Perth', 'Hobart', 'Darwin', 'Canberra'], \n",
    "                 index=['NSW', 'VIC', 'QLD', 'SA', 'WA', 'TAS', 'NT', 'ACT'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can now create a dataframe using the function `pd.DataFrame()`, and passing the argument as a dictionary for the three series. The key for the dictionary (the first argument for each pair) is then used as the name for the columns of the dataframe. Notice that the dataframe is created so that the index of the entries match, and is then ordered based on the index."
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
378
   "execution_count": 12,
Simon Clarke's avatar
Simon Clarke committed
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
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>population</th>\n",
       "      <th>area</th>\n",
       "      <th>capitals</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
409
       "      <td>ACT</td>\n",
Simon Clarke's avatar
Simon Clarke committed
410
411
412
413
414
       "      <td>431215</td>\n",
       "      <td>2358</td>\n",
       "      <td>Canberra</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
415
       "      <td>NSW</td>\n",
Simon Clarke's avatar
Simon Clarke committed
416
417
418
419
420
       "      <td>8166369</td>\n",
       "      <td>801137</td>\n",
       "      <td>Sydney</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
421
       "      <td>NT</td>\n",
Simon Clarke's avatar
Simon Clarke committed
422
423
424
425
426
       "      <td>246500</td>\n",
       "      <td>1334404</td>\n",
       "      <td>Darwin</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
427
       "      <td>QLD</td>\n",
Simon Clarke's avatar
Simon Clarke committed
428
429
430
431
432
       "      <td>5184847</td>\n",
       "      <td>1723030</td>\n",
       "      <td>Brisbane</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
433
       "      <td>SA</td>\n",
Simon Clarke's avatar
Simon Clarke committed
434
435
436
437
438
       "      <td>1770591</td>\n",
       "      <td>979651</td>\n",
       "      <td>Adelaide</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
439
       "      <td>TAS</td>\n",
Simon Clarke's avatar
Simon Clarke committed
440
441
442
443
444
       "      <td>541071</td>\n",
       "      <td>64519</td>\n",
       "      <td>Hobart</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
445
       "      <td>VIC</td>\n",
Simon Clarke's avatar
Simon Clarke committed
446
447
448
449
450
       "      <td>6680648</td>\n",
       "      <td>227038</td>\n",
       "      <td>Melbourne</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
451
       "      <td>WA</td>\n",
Simon Clarke's avatar
Simon Clarke committed
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
       "      <td>2667130</td>\n",
       "      <td>2523924</td>\n",
       "      <td>Perth</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     population     area   capitals\n",
       "ACT      431215     2358   Canberra\n",
       "NSW     8166369   801137     Sydney\n",
       "NT       246500  1334404     Darwin\n",
       "QLD     5184847  1723030   Brisbane\n",
       "SA      1770591   979651   Adelaide\n",
       "TAS      541071    64519     Hobart\n",
       "VIC     6680648   227038  Melbourne\n",
       "WA      2667130  2523924      Perth"
      ]
     },
Simon Clarke's avatar
Simon Clarke committed
472
     "execution_count": 12,
Simon Clarke's avatar
Simon Clarke committed
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "states = pd.DataFrame({'population': population,\n",
    "                       'area': area,\n",
    "                       'capitals': capitals})\n",
    "states"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
488
    "The datatypes for each column are then stored in the property `df.dtypes` (here `df` refers to the name of the current dataframe). In this case, everything is as expected."
Simon Clarke's avatar
Simon Clarke committed
489
490
491
492
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
493
   "execution_count": 13,
Simon Clarke's avatar
Simon Clarke committed
494
495
496
497
498
499
500
501
502
503
504
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "population     int64\n",
       "area           int64\n",
       "capitals      object\n",
       "dtype: object"
      ]
     },
Simon Clarke's avatar
Simon Clarke committed
505
     "execution_count": 13,
Simon Clarke's avatar
Simon Clarke committed
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "states.dtypes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can view other properties of the dataframe, e.g., the column names and the row indices."
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
523
   "execution_count": 14,
Simon Clarke's avatar
Simon Clarke committed
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
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Column names: Index(['population', 'area', 'capitals'], dtype='object')\n",
      "Row indices: Index(['ACT', 'NSW', 'NT', 'QLD', 'SA', 'TAS', 'VIC', 'WA'], dtype='object')\n"
     ]
    }
   ],
   "source": [
    "print('Column names:',states.columns)\n",
    "print('Row indices:',states.index)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The other way to create the dataframe is to specify an array or list as the argument. Here we use an `numpy` array as the argument and use the `values` for the series which have already been defined. We could also explicitly define the arrays. The argument `T` at the end of the array is to take the transpose, i.e., swap the rows with the columns. The first problem that we notice is that because the indices for the capitals are different from that of the other two columns, the capitals are incorrectly assigned."
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
549
   "execution_count": 15,
Simon Clarke's avatar
Simon Clarke committed
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
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>area</th>\n",
       "      <th>population</th>\n",
       "      <th>capitals</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
580
       "      <td>WA</td>\n",
Simon Clarke's avatar
Simon Clarke committed
581
582
583
584
585
       "      <td>2523924</td>\n",
       "      <td>2667130</td>\n",
       "      <td>Sydney</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
586
       "      <td>QLD</td>\n",
Simon Clarke's avatar
Simon Clarke committed
587
588
589
590
591
       "      <td>1723030</td>\n",
       "      <td>5184847</td>\n",
       "      <td>Melbourne</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
592
       "      <td>NT</td>\n",
Simon Clarke's avatar
Simon Clarke committed
593
594
595
596
597
       "      <td>1334404</td>\n",
       "      <td>246500</td>\n",
       "      <td>Brisbane</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
598
       "      <td>SA</td>\n",
Simon Clarke's avatar
Simon Clarke committed
599
600
601
602
603
       "      <td>979651</td>\n",
       "      <td>1770591</td>\n",
       "      <td>Adelaide</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
604
       "      <td>NSW</td>\n",
Simon Clarke's avatar
Simon Clarke committed
605
606
607
608
609
       "      <td>801137</td>\n",
       "      <td>8166369</td>\n",
       "      <td>Perth</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
610
       "      <td>VIC</td>\n",
Simon Clarke's avatar
Simon Clarke committed
611
612
613
614
615
       "      <td>227038</td>\n",
       "      <td>6680648</td>\n",
       "      <td>Hobart</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
616
       "      <td>TAS</td>\n",
Simon Clarke's avatar
Simon Clarke committed
617
618
619
620
621
       "      <td>64519</td>\n",
       "      <td>541071</td>\n",
       "      <td>Darwin</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
622
       "      <td>ACT</td>\n",
Simon Clarke's avatar
Simon Clarke committed
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
       "      <td>2358</td>\n",
       "      <td>431215</td>\n",
       "      <td>Canberra</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        area population   capitals\n",
       "WA   2523924    2667130     Sydney\n",
       "QLD  1723030    5184847  Melbourne\n",
       "NT   1334404     246500   Brisbane\n",
       "SA    979651    1770591   Adelaide\n",
       "NSW   801137    8166369      Perth\n",
       "VIC   227038    6680648     Hobart\n",
       "TAS    64519     541071     Darwin\n",
       "ACT     2358     431215   Canberra"
      ]
     },
Simon Clarke's avatar
Simon Clarke committed
643
     "execution_count": 15,
Simon Clarke's avatar
Simon Clarke committed
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "states_alt = pd.DataFrame(np.array([area.values, population.values, capitals.values]).T,\n",
    "             columns=['area','population','capitals'],\n",
    "             index=['WA', 'QLD', 'NT', 'SA', 'NSW', 'VIC', 'TAS', 'ACT'])\n",
    "states_alt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The second problem is that `numpy` creates an array with all the same data types, and consequently, tries to make everything a string. If we view `df.dtypes` all the columns are `object` (string)."
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
664
   "execution_count": 16,
Simon Clarke's avatar
Simon Clarke committed
665
666
667
668
669
670
671
672
673
674
675
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "area          object\n",
       "population    object\n",
       "capitals      object\n",
       "dtype: object"
      ]
     },
Simon Clarke's avatar
Simon Clarke committed
676
     "execution_count": 16,
Simon Clarke's avatar
Simon Clarke committed
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "states_alt.dtypes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Hence, if you are using an array to create a dataframe, you need to beware of these gotchas. The following cell shows how lists can be used to correctly create the required dataframe."
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
694
   "execution_count": 17,
Simon Clarke's avatar
Simon Clarke committed
695
   "metadata": {},
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
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>area</th>\n",
       "      <th>population</th>\n",
       "      <th>capitals</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
725
       "      <td>WA</td>\n",
726
727
728
729
730
       "      <td>2523924</td>\n",
       "      <td>2667130</td>\n",
       "      <td>Perth</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
731
       "      <td>QLD</td>\n",
732
733
734
735
736
       "      <td>1723030</td>\n",
       "      <td>5184847</td>\n",
       "      <td>Brisbane</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
737
       "      <td>NT</td>\n",
738
739
740
741
742
       "      <td>1334404</td>\n",
       "      <td>246500</td>\n",
       "      <td>Darwin</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
743
       "      <td>SA</td>\n",
744
745
746
747
748
       "      <td>979651</td>\n",
       "      <td>1770591</td>\n",
       "      <td>Adelaide</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
749
       "      <td>NSW</td>\n",
750
751
752
753
754
       "      <td>801137</td>\n",
       "      <td>8166369</td>\n",
       "      <td>Sydney</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
755
       "      <td>VIC</td>\n",
756
757
758
759
760
       "      <td>227038</td>\n",
       "      <td>6680648</td>\n",
       "      <td>Melbourne</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
761
       "      <td>TAS</td>\n",
762
763
764
765
766
       "      <td>64519</td>\n",
       "      <td>541071</td>\n",
       "      <td>Hobart</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
767
       "      <td>ACT</td>\n",
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
       "      <td>2358</td>\n",
       "      <td>431215</td>\n",
       "      <td>Canberra</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        area  population   capitals\n",
       "WA   2523924     2667130      Perth\n",
       "QLD  1723030     5184847   Brisbane\n",
       "NT   1334404      246500     Darwin\n",
       "SA    979651     1770591   Adelaide\n",
       "NSW   801137     8166369     Sydney\n",
       "VIC   227038     6680648  Melbourne\n",
       "TAS    64519      541071     Hobart\n",
       "ACT     2358      431215   Canberra"
      ]
     },
Simon Clarke's avatar
Simon Clarke committed
788
     "execution_count": 17,
789
790
791
792
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
793
794
795
796
797
798
799
800
801
802
   "source": [
    "states_alt = pd.DataFrame([[2523924, 2667130, 'Perth'],\n",
    "                           [1723030, 5184847, 'Brisbane'],\n",
    "                           [1334404, 246500,  'Darwin'],\n",
    "                           [979651,  1770591, 'Adelaide'],\n",
    "                           [801137, 8166369, 'Sydney'],\n",
    "                           [227038, 6680648, 'Melbourne'],\n",
    "                           [64519, 541071, 'Hobart'],\n",
    "                           [2358, 431215, 'Canberra']],\n",
    "                          columns=['area','population','capitals'],\n",
803
804
805
    "                          index=['WA', 'QLD', 'NT', 'SA', 'NSW', 'VIC', 'TAS', 'ACT'])\n",
    "\n",
    "states_alt"
Simon Clarke's avatar
Simon Clarke committed
806
807
808
809
810
811
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
812
    "#### Manipulating Dataframes\n",
Simon Clarke's avatar
Simon Clarke committed
813
814
815
816
817
    "As with series, we can sort dataframes based on specific columns, by using the method `df.sort_values()` and specificing the argument `by`. If we want to sort the dataframe by descending population, then we can use:"
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
818
   "execution_count": 18,
Simon Clarke's avatar
Simon Clarke committed
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
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>population</th>\n",
       "      <th>area</th>\n",
       "      <th>capitals</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
849
       "      <td>NSW</td>\n",
Simon Clarke's avatar
Simon Clarke committed
850
851
852
853
854
       "      <td>8166369</td>\n",
       "      <td>801137</td>\n",
       "      <td>Sydney</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
855
       "      <td>VIC</td>\n",
Simon Clarke's avatar
Simon Clarke committed
856
857
858
859
860
       "      <td>6680648</td>\n",
       "      <td>227038</td>\n",
       "      <td>Melbourne</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
861
       "      <td>QLD</td>\n",
Simon Clarke's avatar
Simon Clarke committed
862
863
864
865
866
       "      <td>5184847</td>\n",
       "      <td>1723030</td>\n",
       "      <td>Brisbane</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
867
       "      <td>WA</td>\n",
Simon Clarke's avatar
Simon Clarke committed
868
869
870
871
872
       "      <td>2667130</td>\n",
       "      <td>2523924</td>\n",
       "      <td>Perth</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
873
       "      <td>SA</td>\n",
Simon Clarke's avatar
Simon Clarke committed
874
875
876
877
878
       "      <td>1770591</td>\n",
       "      <td>979651</td>\n",
       "      <td>Adelaide</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
879
       "      <td>TAS</td>\n",
Simon Clarke's avatar
Simon Clarke committed
880
881
882
883
884
       "      <td>541071</td>\n",
       "      <td>64519</td>\n",
       "      <td>Hobart</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
885
       "      <td>ACT</td>\n",
Simon Clarke's avatar
Simon Clarke committed
886
887
888
889
890
       "      <td>431215</td>\n",
       "      <td>2358</td>\n",
       "      <td>Canberra</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
891
       "      <td>NT</td>\n",
Simon Clarke's avatar
Simon Clarke committed
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
       "      <td>246500</td>\n",
       "      <td>1334404</td>\n",
       "      <td>Darwin</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     population     area   capitals\n",
       "NSW     8166369   801137     Sydney\n",
       "VIC     6680648   227038  Melbourne\n",
       "QLD     5184847  1723030   Brisbane\n",
       "WA      2667130  2523924      Perth\n",
       "SA      1770591   979651   Adelaide\n",
       "TAS      541071    64519     Hobart\n",
       "ACT      431215     2358   Canberra\n",
       "NT       246500  1334404     Darwin"
      ]
     },
Simon Clarke's avatar
Simon Clarke committed
912
     "execution_count": 18,
Simon Clarke's avatar
Simon Clarke committed
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "states.sort_values(by=['population'], ascending=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Operations on the elements of the dataframe are now very easy. For example, if we want to calculate the population density in terms of people per square km, we just need to divide the population column by the area column. This can be assigned to a new column, as shown in the following cell."
   ]
  },
  {
   "cell_type": "code",
Simon Clarke's avatar
Simon Clarke committed
930
   "execution_count": 19,
Simon Clarke's avatar
Simon Clarke committed
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
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>population</th>\n",
       "      <th>area</th>\n",
       "      <th>capitals</th>\n",
       "      <th>density</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
962
       "      <td>ACT</td>\n",
Simon Clarke's avatar
Simon Clarke committed
963
964
965
966
967
968
       "      <td>431215</td>\n",
       "      <td>2358</td>\n",
       "      <td>Canberra</td>\n",
       "      <td>182.873198</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
969
       "      <td>NSW</td>\n",
Simon Clarke's avatar
Simon Clarke committed
970
971
972
973
974
975
       "      <td>8166369</td>\n",
       "      <td>801137</td>\n",
       "      <td>Sydney</td>\n",
       "      <td>10.193474</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
976
       "      <td>NT</td>\n",
Simon Clarke's avatar
Simon Clarke committed
977
978
979
980
981
982
       "      <td>246500</td>\n",
       "      <td>1334404</td>\n",
       "      <td>Darwin</td>\n",
       "      <td>0.184727</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
983
       "      <td>QLD</td>\n",
Simon Clarke's avatar
Simon Clarke committed
984
985
986
987
988
989
       "      <td>5184847</td>\n",
       "      <td>1723030</td>\n",
       "      <td>Brisbane</td>\n",
       "      <td>3.009145</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
990
       "      <td>SA</td>\n",
Simon Clarke's avatar
Simon Clarke committed
991
992
993
994
995
996
       "      <td>1770591</td>\n",
       "      <td>979651</td>\n",
       "      <td>Adelaide</td>\n",
       "      <td>1.807369</td>\n",
       "    </tr>\n",
       "    <tr>\n",
Simon Clarke's avatar
Simon Clarke committed
997
       "      <td>TAS</td>\n",
Simon Clarke's avatar
Simon Clarke committed
998
999
1000
       "      <td>541071</td>\n",
       "      <td>64519</td>\n",
       "      <td>Hobart</td>\n",
For faster browsing, not all history is shown. View entire blame