/
Dataharvest-PythonIV-2.ipynb
610 lines (610 loc) · 19.7 KB
/
Dataharvest-PythonIV-2.ipynb
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
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This tutorial will show you how to load and manipulate files in Python. The key take-away here is the power of scripting. By scripting the file processing, you can batch import many files at once, you can clean-up and add values to your data, and you can repeat the task later when you get new files."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We are going to process a large file from the U.S. Bureau of Labor Statistics, the 2016 annual report on employment for the entire U.S., and all U.S. states and counties, broken down by industry and ownership sector (public employers and private employers).\n",
"\n",
"Our goal is to loop through the rows in this large file (500 MB unzipped) and filter only the rows with data for the U.S., States and counties -- we are going to skip data for metropolitan areas and other niche geographies. \n",
"\n",
"We are also going to filter the detail level - the source data breaks industries down six ways, depending on how detailed we want to get -- for our purposes, the grand total and the mid-level detail (three-digit industry codes) is fine.\n",
"\n",
"Because the industry and geographic area are provided to us as codes, we are going to create a lookup function that will insert columns contained the name of the industry and the geography. \n",
"\n",
"And we are also going to create a function that will attach an 'inflator' in case we want to adjust the dollar amounts for inflation -- in this case, going from 2016 to 2017 isn't such a big deal, remember, this script could be used on other years, and the more you go back in the past, the more inflation is a factor."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To start with, let's create the look-up functions that we will later call when we're doing the actuall file processing."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"create a lookup for the industry title\n",
" download this file \n",
"https://raw.githubusercontent.com/gebelo/training2018/master/industry_titles.csv \n",
"and save it locally... \n",
"in theory, we could have done this step also in Python but doing it this way \n",
"allows you to peruse the file before we work with it.\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"<_csv.reader at 0x10e39c6e0>"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import csv\n",
"# we're going to open the file and turn it into a Python object \n",
"infile=open(\"industry_titles.csv\") #CHANGE THIS TO THE PATH TO YOUR FILE\n",
"# we're going to then convert the object into a Python CSV object, which will give us access to the CSV library of commands\n",
"reader=csv.reader(infile)\n",
"reader"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"['industry_code', 'industry_title']"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# we're going to start at the top of the file and declare the first row to be the headers\n",
"headers=reader.next()\n",
"headers"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"<function close>"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# we're going to create a Python dictionary -- a key, and a value -- that will be our lookup.\n",
"lk_naics={}\n",
"#we're going to loop through the remaining rows in the file and populate our dictionary\n",
"#as we go through the row, the CSV reader is parsing each into two parts, row[0] and row[1]\n",
"for row in reader:\n",
" #what we're doing here is populating lk_naics and setting the first value, row[0] to equal the second value row[1] - but we're getting rid\n",
" #of the string 'NAICS' and the code itself, which would be redundant. And finally, we're getting rid of any\n",
" #extra spaces\n",
" lk_naics[row[0]]=row[1].replace('NAICS','').replace(row[0],'').strip()\n",
"#when we're done, we close the file to cleanup memory \n",
"infile.close"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Other waste collection\n",
"Soybean farming\n"
]
}
],
"source": [
"#these are the kind of lookups we can use when we do the main data import...\n",
"print lk_naics[\"562119\"]\n",
"print lk_naics[\"111110\"]"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"<function close>"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#the entire function\n",
"# we're going to use the Python csv library\n",
"import csv\n",
"# we're going to open the file and turn it into a Python object \n",
"infile=open(\"industry_titles.csv\")\n",
"# we're going to then convert the object into a Python CSV object, which will give us access to the CSV library of commands\n",
"reader=csv.reader(infile)\n",
"# we're going to start at the top of the file and declare the first row to be the headers\n",
"headers=reader.next()\n",
"# we're going to create a Python dictionary -- a key, and a value -- that will be our lookup.\n",
"lk_naics={}\n",
"#we're going to loop through the remaining rows in the file and populate our dictionary\n",
"#as we go through the row, the CSV reader is parsing each into two parts, row[0] and row[1]\n",
"for row in reader:\n",
" #what we're doing here is populating lk_naics and setting the first value, row[0] to equal the second value row[1] - but we're getting rid\n",
" #of the string 'NAICS' and the code itself, which would be redundant. And finally, we're getting rid of any\n",
" #extra spaces\n",
" lk_naics[row[0]]=row[1].replace('NAICS','').replace(row[0],'').strip()\n",
"#when we're done, we close the file to cleanup memory \n",
"infile.close"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Bergen County, New Jersey\n"
]
}
],
"source": [
"#the area titles function is more straightforward\n",
"#download the file from here https://raw.githubusercontent.com/gebelo/training2018/master/area_titles.csv and\n",
"#save it locally\n",
"\n",
"infile=open(\"area_titles.csv\") #CHANGE TO YOUR PATH\n",
"reader=csv.reader(infile)\n",
"headers=reader.next()\n",
"lk_area={}\n",
"for row in reader:\n",
" lk_area[row[0]]=row[1]\n",
" \n",
"infile.close\n",
"\n",
"print lk_area[\"34003\"]\n",
"\n",
"#let's discuss briefly why this worked...."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.0213011\n"
]
}
],
"source": [
"#and lastly, our inflation table\n",
"#grab it from here https://raw.githubusercontent.com/gebelo/training2018/master/inflation.csv\n",
"#note that there are different inflation indexes in here, we're using the one called \"inflator\"\n",
"#which is column index number 2 -- the third column when we start counting with zero\n",
"\n",
"infile=open(\"inflation.csv\")\n",
"reader=csv.reader(infile)\n",
"headers=reader.next()\n",
"lk_inflation={}\n",
"for row in reader:\n",
" lk_inflation[row[0]]=row[2]\n",
"\n",
"\n",
"infile.close\n",
"print lk_inflation[\"2016\"]\n",
"#any questions on why this worked?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" and now for the exciting conclusion of this exercise... let's grab the giant data file \n",
"from the bls web site -- https://data.bls.gov/cew/data/files/2016/csv/2016_annual_singlefile.zip\n",
"unzip the file locally on your computer.\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"let's look at some file layouts and code sheet to see what we're doing\n",
"\n",
"the file layout is here:\n",
"https://data.bls.gov/cew/doc/layouts/csv_annual_layout.htm\n",
"\n",
"it looks like the key variables are columns 1 through 16 -- this means we're only going to import\n",
"python index columns 0 through 15, and then attach our lookup values.\n",
"\n",
"to filter for just the total and three-digit industry codes, we refer to the table here:\n",
"https://data.bls.gov/cew/doc/titles/agglevel/agglevel_titles.htm\n",
"\n",
"for the us, we want levels 10 and 15; for states, 50 and 55; for counties, we want 70 and 75\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'/Users/robertgebeloff/Downloads/2016.annual.singlefile.csv'"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# create a variable with the path to the file\n",
"f='/Users/robertgebeloff/Downloads/2016.annual.singlefile.csv' #CHANGE TO YOUR PATH\n",
"f"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#create new file with the prefix 'new_' attached to the current file's name\n",
"file_out = open(\"/Users/robertgebeloff/Downloads/new_2016.annual.singlefile.csv\", 'w')"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#open original file \n",
"o = open(f)\n",
"#create a Python csv object called 'file_in'\n",
"file_in = csv.reader((o), delimiter=\",\")\n",
"#create a Python object that will write to 'file-out'\n",
"csv_writer = csv.writer(file_out)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"#insert headers from original file into the new file, making room for 3 new columns based on our lookups\n",
"csv_writer.writerow(next(file_in)+[\"area_label\",\"industry_label\",\"inflator\"])\n",
"#loop through the original file, lookup labels and append them to row \n",
"for row in file_in:\n",
" #run our lookups and store reponse in variables\n",
" \n",
" the_area=lk_area[row[0]] # this runs 'area_fips' through our lk_area dictionary\n",
" the_industry=lk_naics[row[2]] # this runs 'industry_code' through our lk_naics dictionary\n",
" the_inflator=lk_inflation[row[5]] # this runs the year for our data through our inflation dictionary\n",
" row=row[0:15]\n",
" row.append(the_area)\n",
" row.append(the_industry)\n",
" row.append(the_inflator)\n",
" \n",
"#write the row with the appendages to the new file only if it's the grand total or a three-digit industry\n",
" if row[3] in (\"10\",\"15\",\"50\",\"55\",\"70\",\"75\"):\n",
" csv_writer.writerow(row)\n",
"\n",
"file_out.close()\n",
"o.close()\n",
"\n",
"#we've gone from 500 mbs to 40 in a few seconds...."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's do one more example -- this time we're going to do some processing on a tab-delimited file. But in addition, we're going to use some string functions to further split apart one of the fields into components.\n",
"\n",
"We're going to use Python to grab the file directly from the Web using the 'requests' library.\n",
"\n",
"And finally, we're going to briefly introduce the Pandas library to peak at our output CSV.\n",
"\n",
"This file is also from the U.S. Bureau of Labor Statistics, the Local Area Unemployment program.\n",
"\n",
"The file layout is here\n",
"https://download.bls.gov/pub/time.series/la/la.txt\n",
"\n",
"The key section:\n",
"\n",
"Field #/Data Element\tLength\t\tValue (Example)\t\t\n",
"\n",
"1. series_id\t\t 20\t\tLASBS060000000000003 \n",
"\n",
"2. year\t\t\t 4\t\t1976\n",
"\n",
"3. period\t\t 3\t\tM01\n",
"\n",
"4. value\t\t 12 \t9.4\n",
"\t\t\t\t \n",
"5. footnote_codes\t 10\t\tIt varies\n",
"\t\t\t\t\n",
"\n",
"The series_id (LASBS060000000000003) can be broken out into:\n",
"\n",
"Code\t\t\t\t\tValue\n",
"\n",
"survey abbreviation\t=\t\tLA\n",
"seasonal\t\t=\t\tS\n",
"area_code\t\t=\t\tBS0600000000000\n",
"measure_code\t\t=\t\t03\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#let's grab the file and save it locally\n",
"import requests # the lib that handles the url stuff\n",
"\n",
"r = requests.get(\"https://download.bls.gov/pub/time.series/la/la.data.0.CurrentU15-19\") \n",
"with open(r'/Users/robertgebeloff/Downloads/lau.txt', 'wb') as f: #change to your path\n",
" f.write(r.content)"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1318605\n"
]
}
],
"source": [
"# how many lines are in there? \n",
"text_file = open(\"/Users/200545/Downloads/lau.txt\", \"r\") #change to your path\n",
"lines = text_file.readlines()\n",
"print len(lines)\n",
"text_file.close()"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#let's convert this into a csv file\n",
"import csv\n",
"#create a csv file\n",
"mycsv = csv.writer(open('/Users/200545/Downloads/lau.csv', 'wb')) #change to your path\n",
"#write out the headers -- note we're going to split the original series id into components areacode and measurecode\n",
"mycsv.writerow(['seriesid', 'areacode','measurecode','year','period','value'])\n",
"#loop through the text file skipping the first row, which has the original headers\n",
"for line in lines[1:len(lines)]:\n",
" #for each row -- split it using the tabs, the first piece is the series id\n",
" seriesid=line.split(\"\\t\")[0]\n",
" #within seriesid, characters 3 through 18 are the area id\n",
" areacode=line.split(\"\\t\")[0][3:18]\n",
" #with the seriesid, characters 18 through 20 are the measurecode\n",
" measurecode=line.split(\"\\t\")[0][18:20]\n",
" #year, period and value are tabs 1,2 and 3 \n",
" year=line.split(\"\\t\")[1]\n",
" period=line.split(\"\\t\")[2]\n",
" value=line.split(\"\\t\")[3]\n",
" #write the row\n",
" mycsv.writerow([seriesid, areacode,measurecode,year,period,value])"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>seriesid</th>\n",
" <th>areacode</th>\n",
" <th>measurecode</th>\n",
" <th>year</th>\n",
" <th>period</th>\n",
" <th>value</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>LAUBS060000000000003</td>\n",
" <td>BS0600000000000</td>\n",
" <td>03</td>\n",
" <td>2015.0</td>\n",
" <td>M01</td>\n",
" <td>7.0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>LAUBS060000000000003</td>\n",
" <td>BS0600000000000</td>\n",
" <td>03</td>\n",
" <td>2015.0</td>\n",
" <td>M02</td>\n",
" <td>6.7</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>LAUBS060000000000003</td>\n",
" <td>BS0600000000000</td>\n",
" <td>03</td>\n",
" <td>2015.0</td>\n",
" <td>M03</td>\n",
" <td>6.6</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>LAUBS060000000000003</td>\n",
" <td>BS0600000000000</td>\n",
" <td>03</td>\n",
" <td>2015.0</td>\n",
" <td>M04</td>\n",
" <td>6.0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>LAUBS060000000000003</td>\n",
" <td>BS0600000000000</td>\n",
" <td>03</td>\n",
" <td>2015.0</td>\n",
" <td>M05</td>\n",
" <td>5.9</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" seriesid areacode measurecode year period value\n",
"0 LAUBS060000000000003 BS0600000000000 03 2015.0 M01 7.0\n",
"1 LAUBS060000000000003 BS0600000000000 03 2015.0 M02 6.7\n",
"2 LAUBS060000000000003 BS0600000000000 03 2015.0 M03 6.6\n",
"3 LAUBS060000000000003 BS0600000000000 03 2015.0 M04 6.0\n",
"4 LAUBS060000000000003 BS0600000000000 03 2015.0 M05 5.9"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#lets open the csv with the Pandas library to see what it looks like\n",
"import pandas as pd\n",
"#this command opens the csv file and assigns datatypes to the columns, string 20, string 15, etc\n",
"laus = pd.read_csv('/Users/200545/Downloads/lau.csv', dtype={'seriesid': 'S20', 'areacode':'S15', 'measurecode':'S2', 'period':'S3'})\n",
"laus.head()\n",
"#this is the Python equivalent of a spreadsheet or database table -- you'll learn more about working with these\n",
"#in later classes"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}