Professional Documents
Culture Documents
Week1
Youarecurrentlylookingatversion1.1ofthisnotebook.Todownloadnotebooksanddatafiles,aswellas
gethelponJupyternotebooksintheCourseraplatform,visittheJupyterNotebookFAQ
(https://www.coursera.org/learn/pythondataanalysis/resources/0dhYG)courseresource.
ThePythonProgrammingLanguage:Functions
In[1]:
x=1
y=2
x+y
Out[1]:
3
In[2]:
x
Out[2]:
1
add_numbersisafunctionthattakestwonumbersandaddsthemtogether.
In[3]:
defadd_numbers(x,y):
returnx+y
add_numbers(1,2)
Out[3]:
3
add_numbersupdatedtotakeanoptional3rdparameter.Usingprintallowsprintingofmultiple
expressionswithinasinglecell.
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
1/45
11/10/2016
Week1
In[4]:
defadd_numbers(x,y,z=None):
if(z==None):
returnx+y
else:
returnx+y+z
print(add_numbers(1,2))
print(add_numbers(1,2,3))
3
6
add_numbersupdatedtotakeanoptionalflagparameter.
In[5]:
defadd_numbers(x,y,z=None,flag=False):
if(flag):
print('Flagistrue!')
if(z==None):
returnx+y
else:
returnx+y+z
print(add_numbers(1,2,flag=True))
Flagistrue!
3
Assignfunctionadd_numberstovariablea.
In[6]:
defadd_numbers(x,y):
returnx+y
a=add_numbers
a(1,2)
Out[6]:
3
ThePythonProgrammingLanguage:Typesand
Sequences
Usetypetoreturntheobject'stype.
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
2/45
11/10/2016
Week1
In[7]:
type('Thisisastring')
Out[7]:
str
In[8]:
type(None)
Out[8]:
NoneType
In[9]:
type(1)
Out[9]:
int
In[10]:
type(1.0)
Out[10]:
float
In[11]:
type(add_numbers)
Out[11]:
function
Tuplesareanimmutabledatastructure(cannotbealtered).
In[12]:
x=(1,'a',2,'b')
type(x)
Out[12]:
tuple
Listsareamutabledatastructure.
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
3/45
11/10/2016
Week1
In[13]:
x=[1,'a',2,'b']
type(x)
Out[13]:
list
Useappendtoappendanobjecttoalist.
In[14]:
x.append(3.3)
print(x)
[1,'a',2,'b',3.3]
Thisisanexampleofhowtoloopthrougheachiteminthelist.
In[15]:
foriteminx:
print(item)
1
a
2
b
3.3
Orusingtheindexingoperator:
In[16]:
i=0
while(i!=len(x)):
print(x[i])
i=i+1
1
a
2
b
3.3
Use+toconcatenatelists.
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
4/45
11/10/2016
Week1
In[17]:
[1,2]+[3,4]
Out[17]:
[1,2,3,4]
Use*torepeatlists.
In[18]:
[1]*3
Out[18]:
[1,1,1]
Usetheinoperatortocheckifsomethingisinsidealist.
In[19]:
1in[1,2,3]
Out[19]:
True
Nowlet'slookatstrings.Usebracketnotationtosliceastring.
In[20]:
x='Thisisastring'
print(x[0])#firstcharacter
print(x[0:1])#firstcharacter,butwehaveexplicitlysettheendcharacter
print(x[0:2])#firsttwocharacters
T
T
Th
Thiswillreturnthelastelementofthestring.
In[21]:
x[1]
Out[21]:
'g'
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
5/45
11/10/2016
Week1
Thiswillreturntheslicestartingfromthe4thelementfromtheendandstoppingbeforethe2ndelement
fromtheend.
In[22]:
x[4:2]
Out[22]:
'ri'
Thisisaslicefromthebeginningofthestringandstoppingbeforethe3rdelement.
In[23]:
x[:3]
Out[23]:
'Thi'
Andthisisaslicestartingfromthe3rdelementofthestringandgoingallthewaytotheend.
In[24]:
x[3:]
Out[24]:
'sisastring'
In[25]:
firstname='Christopher'
lastname='Brooks'
print(firstname+''+lastname)
print(firstname*3)
print('Chris'infirstname)
ChristopherBrooks
ChristopherChristopherChristopher
True
splitreturnsalistofallthewordsinastring,oralistsplitonaspecificcharacter.
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
6/45
11/10/2016
Week1
In[26]:
firstname='ChristopherArthurHansenBrooks'.split('')[0]#[0]selectsthefirstel
ementofthelist
lastname='ChristopherArthurHansenBrooks'.split('')[1]#[1]selectsthelastel
ementofthelist
print(firstname)
print(lastname)
Christopher
Brooks
Makesureyouconvertobjectstostringsbeforeconcatenating.
In[27]:
'Chris'+2
TypeErrorTraceback(mostrecentcalllas
t)
<ipythoninput271623ac76de6e>in<module>()
>1'Chris'+2
TypeError:Can'tconvert'int'objecttostrimplicitly
In[28]:
'Chris'+str(2)
Out[28]:
'Chris2'
Dictionariesassociatekeyswithvalues.
In[29]:
x={'ChristopherBrooks':'brooksch@umich.edu','BillGates':'billg@microsoft.com'}
x['ChristopherBrooks']#Retrieveavaluebyusingtheindexingoperator
Out[29]:
'brooksch@umich.edu'
In[30]:
x['KevynCollinsThompson']=None
x['KevynCollinsThompson']
Iterateoverallofthekeys:
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
7/45
11/10/2016
Week1
In[31]:
fornameinx:
print(x[name])
brooksch@umich.edu
None
billg@microsoft.com
Iterateoverallofthevalues:
In[32]:
foremailinx.values():
print(email)
brooksch@umich.edu
None
billg@microsoft.com
Iterateoveralloftheitemsinthelist:
In[33]:
forname,emailinx.items():
print(name)
print(email)
ChristopherBrooks
brooksch@umich.edu
KevynCollinsThompson
None
BillGates
billg@microsoft.com
Youcanunpackasequenceintodifferentvariables:
In[34]:
x=('Christopher','Brooks','brooksch@umich.edu')
fname,lname,email=x
In[35]:
fname
Out[35]:
'Christopher'
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
8/45
11/10/2016
Week1
In[36]:
lname
Out[36]:
'Brooks'
Makesurethenumberofvaluesyouareunpackingmatchesthenumberofvariablesbeingassigned.
In[37]:
x=('Christopher','Brooks','brooksch@umich.edu','AnnArbor')
fname,lname,email=x
ValueErrorTraceback(mostrecentcalllas
t)
<ipythoninput379ce70064f53e>in<module>()
1x=('Christopher','Brooks','brooksch@umich.edu','AnnArbor')
>2fname,lname,email=x
ValueError:toomanyvaluestounpack(expected3)
ThePythonProgrammingLanguage:Moreon
Strings
In[38]:
print('Chris'+2)
TypeErrorTraceback(mostrecentcalllas
t)
<ipythoninput3882ccfdd3d5d3>in<module>()
>1print('Chris'+2)
TypeError:Can'tconvert'int'objecttostrimplicitly
In[39]:
print('Chris'+str(2))
Chris2
Pythonhasabuiltinmethodforconvenientstringformatting.
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
9/45
11/10/2016
Week1
In[40]:
sales_record={
'price':3.24,
'num_items':4,
'person':'Chris'}
sales_statement='{}bought{}item(s)atapriceof{}eachforatotalof{}'
print(sales_statement.format(sales_record['person'],
sales_record['num_items'],
sales_record['price'],
sales_record['num_items']*sales_record['price']))
Chrisbought4item(s)atapriceof3.24eachforatotalof12.96
ReadingandWritingCSVfiles
Let'simportourdatafilempg.csv,whichcontainsfueleconomydatafor234cars.
mpg:milespergallon
class:carclassification
cty:citympg
cyl:#ofcylinders
displ:enginedisplacementinliters
drv:f=frontwheeldrive,r=rearwheeldrive,4=4wd
fl:fuel(e=ethanolE85,d=diesel,r=regular,p=premium,c=CNG)
hwy:highwaympg
manufacturer:automobilemanufacturer
model:modelofcar
trans:typeoftransmission
year:modelyear
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
10/45
11/10/2016
Week1
In[41]:
importcsv
%precision2
withopen('mpg.csv')ascsvfile:
mpg=list(csv.DictReader(csvfile))
mpg[:3]#Thefirstthreedictionariesinourlist.
Out[41]:
[{'':'1',
'class':'compact',
'cty':'18',
'cyl':'4',
'displ':'1.8',
'drv':'f',
'fl':'p',
'hwy':'29',
'manufacturer':'audi',
'model':'a4',
'trans':'auto(l5)',
'year':'1999'},
{'':'2',
'class':'compact',
'cty':'21',
'cyl':'4',
'displ':'1.8',
'drv':'f',
'fl':'p',
'hwy':'29',
'manufacturer':'audi',
'model':'a4',
'trans':'manual(m5)',
'year':'1999'},
{'':'3',
'class':'compact',
'cty':'20',
'cyl':'4',
'displ':'2',
'drv':'f',
'fl':'p',
'hwy':'31',
'manufacturer':'audi',
'model':'a4',
'trans':'manual(m6)',
'year':'2008'}]
csv.Dictreaderhasreadineachrowofourcsvfileasadictionary.lenshowsthatourlistiscomprised
of234dictionaries.
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
11/45
11/10/2016
Week1
In[42]:
len(mpg)
Out[42]:
234
keysgivesusthecolumnnamesofourcsv.
In[43]:
mpg[0].keys()
Out[43]:
dict_keys(['','fl','hwy','cty','class','model','year','displ','dr
v','trans','manufacturer','cyl'])
Thisishowtofindtheaveragectyfueleconomyacrossallcars.Allvaluesinthedictionariesarestrings,
soweneedtoconverttofloat.
In[44]:
sum(float(d['cty'])fordinmpg)/len(mpg)
Out[44]:
16.86
Similarlythisishowtofindtheaveragehwyfueleconomyacrossallcars.
In[45]:
sum(float(d['hwy'])fordinmpg)/len(mpg)
Out[45]:
23.44
Usesettoreturntheuniquevaluesforthenumberofcylindersthecarsinourdatasethave.
In[46]:
cylinders=set(d['cyl']fordinmpg)
cylinders
Out[46]:
{'4','5','6','8'}
Here'samorecomplexexamplewherewearegroupingthecarsbynumberofcylinder,andfindingthe
averagectympgforeachgroup.
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
12/45
11/10/2016
Week1
In[47]:
CtyMpgByCyl=[]
forcincylinders:#iterateoverallthecylinderlevels
summpg=0
cyltypecount=0
fordinmpg:#iterateoveralldictionaries
ifd['cyl']==c:#ifthecylinderleveltypematches,
summpg+=float(d['cty'])#addthectympg
cyltypecount+=1#incrementthecount
CtyMpgByCyl.append((c,summpg/cyltypecount))#appendthetuple('cylinder','avg
mpg')
CtyMpgByCyl.sort(key=lambdax:x[0])
CtyMpgByCyl
Out[47]:
[('4',21.01),('5',20.50),('6',16.22),('8',12.57)]
Usesettoreturntheuniquevaluesfortheclasstypesinourdataset.
In[48]:
vehicleclass=set(d['class']fordinmpg)#whataretheclasstypes
vehicleclass
Out[48]:
{'2seater','compact','midsize','minivan','pickup','subcompact','su
v'}
Andhere'sanexampleofhowtofindtheaveragehwympgforeachclassofvehicleinourdataset.
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
13/45
11/10/2016
Week1
In[49]:
HwyMpgByClass=[]
fortinvehicleclass:#iterateoverallthevehicleclasses
summpg=0
vclasscount=0
fordinmpg:#iterateoveralldictionaries
ifd['class']==t:#ifthecylinderamounttypematches,
summpg+=float(d['hwy'])#addthehwympg
vclasscount+=1#incrementthecount
HwyMpgByClass.append((t,summpg/vclasscount))#appendthetuple('class','avgm
pg')
HwyMpgByClass.sort(key=lambdax:x[1])
HwyMpgByClass
Out[49]:
[('pickup',16.88),
('suv',18.13),
('minivan',22.36),
('2seater',24.80),
('midsize',27.29),
('subcompact',28.14),
('compact',28.30)]
ThePythonProgrammingLanguage:Datesand
Times
In[50]:
importdatetimeasdt
importtimeastm
timereturnsthecurrenttimeinsecondssincetheEpoch.(January1st,1970)
In[51]:
tm.time()
Out[51]:
1478786894.77
Convertthetimestamptodatetime.
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
14/45
11/10/2016
Week1
In[52]:
dtnow=dt.datetime.fromtimestamp(tm.time())
dtnow
Out[52]:
datetime.datetime(2016,11,10,14,8,15,964154)
Handydatetimeattributes:
In[53]:
dtnow.year,dtnow.month,dtnow.day,dtnow.hour,dtnow.minute,dtnow.second#getyear,
month,day,etc.fromadatetime
Out[53]:
(2016,11,10,14,8,15)
timedeltaisadurationexpressingthedifferencebetweentwodates.
In[54]:
delta=dt.timedelta(days=100)#createatimedeltaof100days
delta
Out[54]:
datetime.timedelta(100)
date.todayreturnsthecurrentlocaldate.
In[55]:
today=dt.date.today()
In[56]:
todaydelta#thedate100daysago
Out[56]:
datetime.date(2016,8,2)
In[57]:
today>todaydelta#comparedates
Out[57]:
True
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
15/45
11/10/2016
Week1
ThePythonProgrammingLanguage:Objectsand
map()
Anexampleofaclassinpython:
In[58]:
classPerson:
department='SchoolofInformation'#aclassvariable
defset_name(self,new_name):#amethod
self.name=new_name
defset_location(self,new_location):
self.location=new_location
In[59]:
person=Person()
person.set_name('ChristopherBrooks')
person.set_location('AnnArbor,MI,USA')
print('{}livein{}andworksinthedepartment{}'.format(person.name,person.locatio
n,person.department))
ChristopherBrooksliveinAnnArbor,MI,USAandworksinthedepartment
SchoolofInformation
Here'sanexampleofmappingtheminfunctionbetweentwolists.
In[62]:
store1=[10.00,11.00,12.34,2.34]
store2=[9.00,11.10,12.34,2.01]
cheapest=map(min,store1,store2)
cheapest
Out[62]:
<mapat0x7f9d081625c0>
Nowlet'siteratethroughthemapobjecttoseethevalues.
In[63]:
foritemincheapest:
print(item)
9.0
11.0
12.34
2.01
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
16/45
11/10/2016
Week1
ThePythonProgrammingLanguage:LambdaandList
Comprehensions
Here'sanexampleoflambdathattakesinthreeparametersandaddsthefirsttwo.
In[64]:
my_function=lambdaa,b,c:a+b
In[65]:
my_function(1,2,3)
Out[65]:
3
Let'siteratefrom0to999andreturntheevennumbers.
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
17/45
11/10/2016
Week1
In[66]:
my_list=[]
fornumberinrange(0,1000):
ifnumber%2==0:
my_list.append(number)
my_list
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
18/45
11/10/2016
Week1
Out[66]:
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
19/45
11/10/2016
Week1
[0,
2,
4,
6,
8,
10,
12,
14,
16,
18,
20,
22,
24,
26,
28,
30,
32,
34,
36,
38,
40,
42,
44,
46,
48,
50,
52,
54,
56,
58,
60,
62,
64,
66,
68,
70,
72,
74,
76,
78,
80,
82,
84,
86,
88,
90,
92,
94,
96,
98,
100,
102,
104,
106,
108,
110,
112,
114,
116,
118,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
20/45
11/10/2016
118,
120,
Week1
122,
124,
126,
128,
130,
132,
134,
136,
138,
140,
142,
144,
146,
148,
150,
152,
154,
156,
158,
160,
162,
164,
166,
168,
170,
172,
174,
176,
178,
180,
182,
184,
186,
188,
190,
192,
194,
196,
198,
200,
202,
204,
206,
208,
210,
212,
214,
216,
218,
220,
222,
224,
226,
228,
230,
232,
234,
236,
238,
240,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
21/45
11/10/2016
240,
242,
Week1
244,
246,
248,
250,
252,
254,
256,
258,
260,
262,
264,
266,
268,
270,
272,
274,
276,
278,
280,
282,
284,
286,
288,
290,
292,
294,
296,
298,
300,
302,
304,
306,
308,
310,
312,
314,
316,
318,
320,
322,
324,
326,
328,
330,
332,
334,
336,
338,
340,
342,
344,
346,
348,
350,
352,
354,
356,
358,
360,
362,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
22/45
11/10/2016
362,
364,
Week1
366,
368,
370,
372,
374,
376,
378,
380,
382,
384,
386,
388,
390,
392,
394,
396,
398,
400,
402,
404,
406,
408,
410,
412,
414,
416,
418,
420,
422,
424,
426,
428,
430,
432,
434,
436,
438,
440,
442,
444,
446,
448,
450,
452,
454,
456,
458,
460,
462,
464,
466,
468,
470,
472,
474,
476,
478,
480,
482,
484,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
23/45
11/10/2016
484,
486,
Week1
488,
490,
492,
494,
496,
498,
500,
502,
504,
506,
508,
510,
512,
514,
516,
518,
520,
522,
524,
526,
528,
530,
532,
534,
536,
538,
540,
542,
544,
546,
548,
550,
552,
554,
556,
558,
560,
562,
564,
566,
568,
570,
572,
574,
576,
578,
580,
582,
584,
586,
588,
590,
592,
594,
596,
598,
600,
602,
604,
606,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
24/45
11/10/2016
606,
608,
Week1
610,
612,
614,
616,
618,
620,
622,
624,
626,
628,
630,
632,
634,
636,
638,
640,
642,
644,
646,
648,
650,
652,
654,
656,
658,
660,
662,
664,
666,
668,
670,
672,
674,
676,
678,
680,
682,
684,
686,
688,
690,
692,
694,
696,
698,
700,
702,
704,
706,
708,
710,
712,
714,
716,
718,
720,
722,
724,
726,
728,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
25/45
11/10/2016
728,
730,
Week1
732,
734,
736,
738,
740,
742,
744,
746,
748,
750,
752,
754,
756,
758,
760,
762,
764,
766,
768,
770,
772,
774,
776,
778,
780,
782,
784,
786,
788,
790,
792,
794,
796,
798,
800,
802,
804,
806,
808,
810,
812,
814,
816,
818,
820,
822,
824,
826,
828,
830,
832,
834,
836,
838,
840,
842,
844,
846,
848,
850,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
26/45
11/10/2016
850,
852,
Week1
854,
856,
858,
860,
862,
864,
866,
868,
870,
872,
874,
876,
878,
880,
882,
884,
886,
888,
890,
892,
894,
896,
898,
900,
902,
904,
906,
908,
910,
912,
914,
916,
918,
920,
922,
924,
926,
928,
930,
932,
934,
936,
938,
940,
942,
944,
946,
948,
950,
952,
954,
956,
958,
960,
962,
964,
966,
968,
970,
972,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
27/45
11/10/2016
972,
974,
Week1
976,
978,
980,
982,
984,
986,
988,
990,
992,
994,
996,
998]
Nowthesamethingbutwithlistcomprehension.
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
28/45
11/10/2016
Week1
In[67]:
my_list=[numberfornumberinrange(0,1000)ifnumber%2==0]
my_list
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
29/45
11/10/2016
Week1
Out[67]:
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
30/45
11/10/2016
Week1
[0,
2,
4,
6,
8,
10,
12,
14,
16,
18,
20,
22,
24,
26,
28,
30,
32,
34,
36,
38,
40,
42,
44,
46,
48,
50,
52,
54,
56,
58,
60,
62,
64,
66,
68,
70,
72,
74,
76,
78,
80,
82,
84,
86,
88,
90,
92,
94,
96,
98,
100,
102,
104,
106,
108,
110,
112,
114,
116,
118,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
31/45
11/10/2016
118,
120,
Week1
122,
124,
126,
128,
130,
132,
134,
136,
138,
140,
142,
144,
146,
148,
150,
152,
154,
156,
158,
160,
162,
164,
166,
168,
170,
172,
174,
176,
178,
180,
182,
184,
186,
188,
190,
192,
194,
196,
198,
200,
202,
204,
206,
208,
210,
212,
214,
216,
218,
220,
222,
224,
226,
228,
230,
232,
234,
236,
238,
240,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
32/45
11/10/2016
240,
242,
Week1
244,
246,
248,
250,
252,
254,
256,
258,
260,
262,
264,
266,
268,
270,
272,
274,
276,
278,
280,
282,
284,
286,
288,
290,
292,
294,
296,
298,
300,
302,
304,
306,
308,
310,
312,
314,
316,
318,
320,
322,
324,
326,
328,
330,
332,
334,
336,
338,
340,
342,
344,
346,
348,
350,
352,
354,
356,
358,
360,
362,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
33/45
11/10/2016
362,
364,
Week1
366,
368,
370,
372,
374,
376,
378,
380,
382,
384,
386,
388,
390,
392,
394,
396,
398,
400,
402,
404,
406,
408,
410,
412,
414,
416,
418,
420,
422,
424,
426,
428,
430,
432,
434,
436,
438,
440,
442,
444,
446,
448,
450,
452,
454,
456,
458,
460,
462,
464,
466,
468,
470,
472,
474,
476,
478,
480,
482,
484,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
34/45
11/10/2016
484,
486,
Week1
488,
490,
492,
494,
496,
498,
500,
502,
504,
506,
508,
510,
512,
514,
516,
518,
520,
522,
524,
526,
528,
530,
532,
534,
536,
538,
540,
542,
544,
546,
548,
550,
552,
554,
556,
558,
560,
562,
564,
566,
568,
570,
572,
574,
576,
578,
580,
582,
584,
586,
588,
590,
592,
594,
596,
598,
600,
602,
604,
606,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
35/45
11/10/2016
606,
608,
Week1
610,
612,
614,
616,
618,
620,
622,
624,
626,
628,
630,
632,
634,
636,
638,
640,
642,
644,
646,
648,
650,
652,
654,
656,
658,
660,
662,
664,
666,
668,
670,
672,
674,
676,
678,
680,
682,
684,
686,
688,
690,
692,
694,
696,
698,
700,
702,
704,
706,
708,
710,
712,
714,
716,
718,
720,
722,
724,
726,
728,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
36/45
11/10/2016
728,
730,
Week1
732,
734,
736,
738,
740,
742,
744,
746,
748,
750,
752,
754,
756,
758,
760,
762,
764,
766,
768,
770,
772,
774,
776,
778,
780,
782,
784,
786,
788,
790,
792,
794,
796,
798,
800,
802,
804,
806,
808,
810,
812,
814,
816,
818,
820,
822,
824,
826,
828,
830,
832,
834,
836,
838,
840,
842,
844,
846,
848,
850,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
37/45
11/10/2016
850,
852,
Week1
854,
856,
858,
860,
862,
864,
866,
868,
870,
872,
874,
876,
878,
880,
882,
884,
886,
888,
890,
892,
894,
896,
898,
900,
902,
904,
906,
908,
910,
912,
914,
916,
918,
920,
922,
924,
926,
928,
930,
932,
934,
936,
938,
940,
942,
944,
946,
948,
950,
952,
954,
956,
958,
960,
962,
964,
966,
968,
970,
972,
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
38/45
11/10/2016
972,
974,
Week1
976,
978,
980,
982,
984,
986,
988,
990,
992,
994,
996,
998]
ThePythonProgrammingLanguage:Numerical
Python(NumPy)
In[68]:
importnumpyasnp
CreatingArrays
Createalistandconvertittoanumpyarray
In[69]:
mylist=[1,2,3]
x=np.array(mylist)
x
Out[69]:
array([1,2,3])
Orjustpassinalistdirectly
In[70]:
y=np.array([4,5,6])
y
Out[70]:
array([4,5,6])
Passinalistofliststocreateamultidimensionalarray.
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
39/45
11/10/2016
Week1
In[71]:
m=np.array([[7,8,9],[10,11,12]])
m
Out[71]:
array([[7,8,9],
[10,11,12]])
Usetheshapemethodtofindthedimensionsofthearray.(rows,columns)
In[72]:
m.shape
Out[72]:
(2,3)
arangereturnsevenlyspacedvalueswithinagiveninterval.
In[73]:
n=np.arange(0,30,2)#startat0countupby2,stopbefore30
n
Out[73]:
array([0,2,4,6,8,10,12,14,16,18,20,22,24,26,28])
reshapereturnsanarraywiththesamedatawithanewshape.
In[74]:
n=n.reshape(3,5)#reshapearraytobe3x5
n
Out[74]:
array([[0,2,4,6,8],
[10,12,14,16,18],
[20,22,24,26,28]])
linspacereturnsevenlyspacednumbersoveraspecifiedinterval.
In[75]:
o=np.linspace(0,4,9)#return9evenlyspacedvaluesfrom0to4
o
Out[75]:
array([0.,0.5,1.,1.5,2.,2.5,3.,3.5,4.])
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
40/45
11/10/2016
Week1
resizechangestheshapeandsizeofarrayinplace.
In[76]:
o.resize(3,3)
o
Out[76]:
array([[0.,0.5,1.],
[1.5,2.,2.5],
[3.,3.5,4.]])
onesreturnsanewarrayofgivenshapeandtype,filledwithones.
In[77]:
np.ones((3,2))
Out[77]:
array([[1.,1.],
[1.,1.],
[1.,1.]])
zerosreturnsanewarrayofgivenshapeandtype,filledwithzeros.
In[78]:
np.zeros((2,3))
Out[78]:
array([[0.,0.,0.],
[0.,0.,0.]])
eyereturnsa2Darraywithonesonthediagonalandzeroselsewhere.
In[79]:
np.eye(3)
Out[79]:
array([[1.,0.,0.],
[0.,1.,0.],
[0.,0.,1.]])
diagextractsadiagonalorconstructsadiagonalarray.
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
41/45
11/10/2016
Week1
In[80]:
np.diag(y)
Out[80]:
array([[4,0,0],
[0,5,0],
[0,0,6]])
Createanarrayusingrepeatinglist(orseenp.tile)
In[81]:
np.array([1,2,3]*3)
Out[81]:
array([1,2,3,1,2,3,1,2,3])
Repeatelementsofanarrayusingrepeat.
In[82]:
np.repeat([1,2,3],3)
Out[82]:
array([1,1,1,2,2,2,3,3,3])
CombiningArrays
In[83]:
p=np.ones([2,3],int)
p
Out[83]:
array([[1,1,1],
[1,1,1]])
Usevstacktostackarraysinsequencevertically(rowwise).
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
42/45
11/10/2016
Week1
In[84]:
np.vstack([p,2*p])
Out[84]:
array([[1,1,1],
[1,1,1],
[2,2,2],
[2,2,2]])
Usehstacktostackarraysinsequencehorizontally(columnwise).
In[85]:
np.hstack([p,2*p])
Out[85]:
array([[1,1,1,2,2,2],
[1,1,1,2,2,2]])
Operations
Use+,,*,/and**toperformelementwiseaddition,subtraction,multiplication,divisionandpower.
In[86]:
print(x+y)#elementwiseaddition[123]+[456]=[579]
print(xy)#elementwisesubtraction[123][456]=[333]
[579]
[333]
In[87]:
print(x*y)#elementwisemultiplication[123]*[456]=[41018]
print(x/y)#elementwisedivison[123]/[456]=[0.250.40.5]
[41018]
[0.250.40.5]
In[88]:
print(x**2)#elementwisepower[123]^2=[149]
[149]
DotProduct:
y1
[ x 1 x 2 x 3 ] y2 = x 1 y1 + x 2 y2 + x 3 y3
y3
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
43/45
11/10/2016
Week1
In[89]:
x.dot(y)#dotproduct1*4+2*5+3*6
Out[89]:
32
In[90]:
z=np.array([y,y**2])
print(len(z))#numberofrowsofarray
2
Let'slookattransposingarrays.Transposingpermutesthedimensionsofthearray.
In[91]:
z=np.array([y,y**2])
z
Out[91]:
array([[4,5,6],
[16,25,36]])
Theshapeofarrayzis(2,3)beforetransposing.
In[92]:
z.shape
Out[92]:
(2,3)
Use.Ttogetthetranspose.
In[93]:
z.T
Out[93]:
array([[4,16],
[5,25],
[6,36]])
Thenumberofrowshasswappedwiththenumberofcolumns.
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
44/45
11/10/2016
Week1
In[94]:
z.T.shape
Out[94]:
(3,2)
Use.dtypetoseethedatatypeoftheelementsinthearray.
In[95]:
z.dtype
Out[95]:
dtype('int64')
Use.astypetocasttoaspecifictype.
In[96]:
z=z.astype('f')
z.dtype
Out[96]:
dtype('float32')
MathFunctions
Numpyhasmanybuiltinmathfunctionsthatcanbeperformedonarrays.
In[97]:
a=np.array([4,2,1,3,5])
In[98]:
a.sum()
Out[98]:
3
In[99]:
a.max()
Out[99]:
5
https://hub.courseranotebooks.org/user/jlapqpmgcmbfygnmluswdg/nbconvert/html/Week%201.ipynb?download=false
45/45