Comandos PYTHON - Numpy Example List
Comandos PYTHON - Numpy Example List
ThispagecontainsalargedatabaseofexamplesdemonstratingmostoftheNumpy
functionality.NumpyExampleListWithDochastheseexamplesinterleavedwiththe
builtindocumentation,butisnotasregularlyupdatedasthispage.Theexampleshere
canbeeasilyaccessedfromPythonusingtheNumpyExampleFetcher.
Thisexamplelistisincrediblyuseful,andwewouldliketogetallthegoodexamples
andcommentsintegratedintheofficialnumpydocumentationsothattheyarealso
shippedwithnumpy.Youcanhelp.Theofficialnumpydocumentationcanbeedited
onhttp://docs.scipy.org.
TabladeContenidos
1. ...
2. []
3. abs()
4. absolute()
5. accumulate()
6. add()
7. all()
8. allclose()
9. alltrue()
10. angle()
11. any()
12. append()
13. apply_along_axis()
14. apply_over_axes()
15. arange()
16. arccos()
17. arccosh()
18. arcsin()
19. arcsinh()
20. arctan()
21. arctan2()
22. arctanh()
23. argmax()
24. argmin()
25. argsort()
26. array()
27. arrayrange()
28. array_split()
29. asarray()
30. asanyarray()
31. asmatrix()
32. astype()
33. atleast_1d()
34. atleast_2d()
35. atleast_3d()
36. average()
37. beta()
38. binary_repr()
39. bincount()
40. binomial()
41. bitwise_and()
42. bitwise_or()
43. bitwise_xor()
44. bmat()
45. broadcast()
46. bytes()
47. c_[]
48. cast[]()
49. ceil()
50. choose()
51. clip()
52. column_stack()
53. compress()
54. concatenate()
55. conj()
56. conjugate()
57. copy()
58. corrcoef()
59. cos()
60. cov()
61. cross()
62. cumprod()
63. cumsum()
64. delete()
65. det()
66. diag()
67. diagflat()
68. diagonal()
69. diff()
70. digitize()
71. dot()
72. dsplit()
73. dstack()
74. dtype()
75. empty()
76. empty_like()
77. expand_dims()
78. eye()
79. fft()
80. fftfreq()
81. fftshift()
82. fill()
83. finfo()
84. fix()
85. flat
86. flatten()
87. fliplr()
88. flipud()
89. floor()
90. fromarrays()
91. frombuffer()
92. fromfile()
93. fromfunction()
94. fromiter()
95. generic
96. gumbel()
97. histogram()
98. hsplit()
99. hstack()
100. hypot()
101. identity()
102. ifft()
103. imag
104. index_exp[]
105. indices()
106. inf
107. inner()
108. insert()
109. inv()
110. iscomplex()
111. iscomplexobj()
112. item()
113. ix_()
114. lexsort()
115. linspace()
116. loadtxt()
117. logical_and()
118. logical_not()
119. logical_or()
120. logical_xor()
121. logspace()
122. lstsq()
123. mat()
124. matrix()
125. max()
126. maximum()
127. mean()
128. median()
129. mgrid[]
130. min()
131. minimum()
132. multiply()
133. nan
134. ndenumerate()
135. ndim
136. ndindex()
137. newaxis
138. nonzero()
139. ogrid()
140. ones()
141. ones_like()
142. outer()
143. permutation()
144. piecewise()
145. pinv()
146. poisson()
147. poly1d()
148. polyfit()
149. prod()
150. ptp()
151. put()
152. putmask()
153. r_[]
154. rand()
155. randint()
156. randn()
157. random_integers()
158. random_sample()
159. ranf()
160. ravel()
161. real
162. recarray()
163. reduce()
164. repeat()
165. reshape()
166. resize()
167. rollaxis()
168. round()
169. rot90()
170. s_[]
171. sample()
172. savetxt()
173. searchsorted()
174. seed()
175. select()
176. set_printoptions()
177. shape
178. shuffle()
179. slice()
180. solve()
181. sometrue()
182. sort()
183. split()
184. squeeze()
185. std()
186. standard_normal()
187. sum()
188. svd()
189. swapaxes()
190. T
191. take()
192. tensordot()
193. tile()
194. tofile()
195. tolist()
196. trace()
197. transpose()
198. tri()
199. tril()
200. trim_zeros()
201. triu()
202. typeDict()
203. uniform()
204. unique()
205. unique1d()
206. vander()
207. var()
208. vdot()
209. vectorize()
210. view()
211. vonmises()
212. vsplit()
213. vstack()
214. weibull()
215. where()
216. zeros()
217. zeros_like()
...
>>>fromnumpyimport*
>>>a=arange(12)
>>>a=a.reshape(3,2,2)
>>>printa
[[[01]
[23]]
[[45]
[67]]
[[89]
[1011]]]
>>>a[...,0]#sameasa[:,:,0]
array([[0,2],
[4,6],
[8,10]])
>>>a[1:,...]#sameasa[1:,:,:]orjusta[1:]
array([[[4,5],
[6,7]],
[[8,9],
[10,11]]])
Seealso:[],newaxis
[]
>>>fromnumpyimport*
>>>a=array([[0,1,2,3,4],
...[10,11,12,13,14],
...[20,21,22,23,24],
...[30,31,32,33,34]])
>>>
>>>a[0,0]#indicesstartbyzero
0
>>>a[1]#lastrow
array([30,31,32,33,34])
>>>a[1:3,1:4]#subarray
array([[11,12,13],
[21,22,23]])
>>>
>>>i=array([0,1,2,1])#arrayofindicesforthefirstaxis
>>>j=array([1,2,3,4])#arrayofindicesforthesecondaxis
>>>a[i,j]
array([1,12,23,14])
>>>
>>>a[a<13]#booleanindexing
array([0,1,2,3,4,10,11,12])
>>>
>>>b1=array([True,False,True,False])#booleanrowselector
>>>a[b1,:]
array([[0,1,2,3,4],
[20,21,22,23,24]])
>>>
>>>b2=array([False,True,True,False,True])#booleancolumn
selector
>>>a[:,b2]
array([[1,2,4],
[11,12,14],
[21,22,24],
[31,32,34]])
Seealso:...,newaxis,ix_,indices,nonzero,where,slice
abs()
>>>fromnumpyimport*
>>>abs(1)
1
>>>abs(array([1.2,1.2]))
array([1.2,1.2])
>>>abs(1.2+1j)
1.5620499351813308
Seealso:absolute,angle
absolute()
Synonymforabs()
Seeabs
accumulate()
>>>fromnumpyimport*
>>>add.accumulate(array([1.,2.,3.,4.]))#likereduce()butalso
givesintermediateresults
array([1.,3.,6.,10.])
>>>array([1.,1.+2.,(1.+2.)+3.,((1.+2.)+3.)+4.])#thisiswhat
itcomputed
array([1.,3.,6.,10.])
>>>multiply.accumulate(array([1.,2.,3.,4.]))#worksalsowith
otheroperands
array([1.,2.,6.,24.])
>>>array([1.,1.*2.,(1.*2.)*3.,((1.*2.)*3.)*4.])#thisiswhat
itcomputed
array([1.,2.,6.,24.])
>>>add.accumulate(array([[1,2,3],[4,5,6]]),axis=0)#
accumulateeverycolumnseparately
array([[1,2,3],
[5,7,9]])
>>>add.accumulate(array([[1,2,3],[4,5,6]]),axis=1)#
accumulateeveryrowseparately
array([[1,3,6],
[4,9,15]])
Seealso:reduce,cumprod,cumsum
add()
>>>fromnumpyimport*
>>>add(array([1.2,1.2]),array([1,3]))
array([0.2,4.2])
>>>array([1.2,1.2])+array([1,3])
array([0.2,4.2])
all()
>>>fromnumpyimport*
>>>a=array([True,False,True])
>>>a.all()#ifallelementsofaareTrue:returnTrue
otherwiseFalse
False
>>>all(a)#thisformalsoexists
False
>>>a=array([1,2,3])
>>>all(a>0)#equivalentto(a>0).all()
True
Seealso:any,alltrue,sometrue
allclose()
>>>allclose(array([1e10,1e7]),array([1.00001e10,1e8]))
False
>>>allclose(array([1e10,1e8]),array([1.00001e10,1e9]))
True
>>>allclose(array([1e10,1e8]),array([1.0001e10,1e9]))
False
alltrue()
>>>fromnumpyimport*
>>>b=array([True,False,True,True])
>>>alltrue(b)
False
>>>a=array([1,5,2,7])
>>>alltrue(a>=5)
False
Seealso:sometrue,all,any
angle()
>>>fromnumpyimport*
>>>angle(1+1j)#inradians
0.78539816339744828
>>>angle(1+1j,deg=True)#indegrees
45.0
Seealso:real,imag,hypot
any()
>>>fromnumpyimport*
>>>a=array([True,False,True])
>>>a.any()#givesTrueifatleast1elementofaisTrue,
otherwiseFalse
True
>>>any(a)#thisformalsoexists
True
>>>a=array([1,2,3])
>>>(a>=1).any()#equivalenttoany(a>=1)
True
Seealso:all,alltrue,sometrue
append()
>>>fromnumpyimport*
>>>a=array([10,20,30,40])
>>>append(a,50)
array([10,20,30,40,50])
>>>append(a,[50,60])
array([10,20,30,40,50,60])
>>>a=array([[10,20,30],[40,50,60],[70,80,90]])
>>>append(a,[[15,15,15]],axis=0)
array([[10,20,30],
[40,50,60],
[70,80,90],
[15,15,15]])
>>>append(a,[[15],[15],[15]],axis=1)
array([[10,20,30,15],
[40,50,60,15],
[70,80,90,15]])
Seealso:insert,delete,concatenate
apply_along_axis()
>>>fromnumpyimport*
>>>defmyfunc(a):#functionworksona1darrays,takesthe
averageofthe1stanlastelement
...return(a[0]+a[1])/2
...
>>>b=array([[1,2,3],[4,5,6],[7,8,9]])
>>>apply_along_axis(myfunc,0,b)#applymyfunctoeachcolumn
(axis=0)ofb
array([4,5,6])
>>>apply_along_axis(myfunc,1,b)#applymyfunctoeachrow
(axis=1)ofb
array([2,5,8])
Seealso:apply_over_axes,vectorize
apply_over_axes()
>>>fromnumpyimport*
>>>a=arange(24).reshape(2,3,4)#ahas3axes:0,1and2
>>>a
array([[[0,1,2,3],
[4,5,6,7],
[8,9,10,11]],
[[12,13,14,15],
[16,17,18,19],
[20,21,22,23]]])
>>>apply_over_axes(sum,a,[0,2])#sumoverallaxesexcept
axis=1,resulthassameshapeasoriginal
array([[[60],
[92],
[124]]])
Seealso:apply_along_axis,vectorize
arange()
>>>fromnumpyimport*
>>>arange(3)
array([0,1,2])
>>>arange(3.0)
array([0.,1.,2.])
>>>arange(3,dtype=float)
array([0.,1.,2.])
>>>arange(3,10)#start,stop
array([3,4,5,6,7,8,9])
>>>arange(3,10,2)#start,stop,step
array([3,5,7,9])
Seealso:r_,linspace,logspace,mgrid,ogrid
arccos()
>>>fromnumpyimport*
>>>arccos(array([0,1]))
array([1.57079633,0.])
Seealso:arcsin,arccosh,arctan,arctan2
arccosh()
>>>fromnumpyimport*
>>>arccosh(array([e,10.0]))
array([1.65745445,2.99322285])
Seealso:arccos,arcsinh,arctanh
arcsin()
>>>fromnumpyimport*
>>>arcsin(array([0,1]))
array([0.,1.57079633])
Seealso:arccos,arctan,arcsinh
arcsinh()
>>>fromnumpyimport*
>>>arcsinh(array([e,10.0]))
array([1.72538256,2.99822295])
Seealso:arccosh,arcsin,arctanh
arctan()
>>>fromnumpyimport*
>>>arctan(array([0,1]))
array([0.,0.78539816])
Seealso:arccos,arcsin,arctanh
arctan2()
>>>fromnumpyimport*
>>>arctan2(array([0,1]),array([1,0]))
array([0.,1.57079633])
Seealso:arcsin,arccos,arctan,arctanh
arctanh()
>>>fromnumpyimport*
>>>arctanh(array([0,0.5]))
array([0.,0.54930614])
Seealso:arcsinh,arccosh,arctan,arctan2
argmax()
>>>fromnumpyimport*
>>>a=array([10,20,30])
>>>maxindex=a.argmax()
>>>a[maxindex]
30
>>>a=array([[10,50,30],[60,20,40]])
>>>maxindex=a.argmax()
>>>maxindex
3
>>>a.ravel()[maxindex]
60
>>>a.argmax(axis=0)#foreachcolumn:therowindexofthe
maximumvalue
array([1,0,1])
>>>a.argmax(axis=1)#foreachrow:thecolumnindexofthe
maximumvalue
array([1,0])
>>>argmax(a)#alsoexists,slower,defaultisaxis=1
array([1,0])
Seealso:argmin,nan,min,max,maximum,minimum
argmin()
>>>fromnumpyimport*
>>>a=array([10,20,30])
>>>minindex=a.argmin()
>>>a[minindex]
10
>>>a=array([[10,50,30],[60,20,40]])
>>>minindex=a.argmin()
>>>minindex
0
>>>a.ravel()[minindex]
10
>>>a.argmin(axis=0)#foreachcolumn:therowindexofthe
minimumvalue
array([0,1,0])
>>>a.argmin(axis=1)#foreachrow:thecolumnindexofthe
minimumvalue
array([0,1])
>>>argmin(a)#alsoexists,slower,defaultisaxis=1
array([0,1])
Seealso:argmax,nan,min,max,maximum,minimum
argsort()
argsort(axis=1,kind="quicksort")
>>>fromnumpyimport*
>>>a=array([2,0,8,4,1])
>>>ind=a.argsort()#indicesofsortedarrayusingquicksort
(default)
>>>ind
array([1,4,0,3,2])
>>>a[ind]#sameeffectasa.sort()
array([0,1,2,4,8])
>>>ind=a.argsort(kind='merge')#algorithmoptionsare
'quicksort','mergesort'and'heapsort'
>>>a=array([[8,4,1],[2,0,9]])
>>>ind=a.argsort(axis=0)#sortsoncolumns.NOTthesameas
a.sort(axis=1)
>>>ind
array([[1,1,0],
[0,0,1]])
>>>a[ind,[[0,1,2],[0,1,2]]]#2Darraysneedfancyindexingif
youwanttosortthem.
array([[2,0,1],
[8,4,9]])
>>>ind=a.argsort(axis=1)#sortalongrows.Canuse
a.argsort(axis=1)forlastaxis.
>>>ind
array([[2,1,0],
[1,0,2]])
>>>a=ones(17)
>>>a.argsort()#quicksortdoesn'tpreserveoriginalorder.
array([0,14,13,12,11,10,9,15,8,6,5,4,3,2,1,7,16])
>>>a.argsort(kind="mergesort")#mergesortpreservesorderwhen
possible.Itisastablesort.
array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
>>>ind=argsort(a)#thereisafunctionalform
Seealso:lexsort,sort
array()
>>>fromnumpyimport*
>>>array([1,2,3])#conversionfromalisttoanarray
array([1,2,3])
>>>array([1,2,3],dtype=complex)#outputtypeisspecified
array([1.+0.j,2.+0.j,3.+0.j])
>>>array(1,copy=0,subok=1,ndmin=1)#basicallyequivalentto
atleast_1d
array([1])
>>>array(1,copy=0,subok=1,ndmin=2)#basicallyequivalentto
atleast_2d
array([[1]])
>>>array(1,subok=1,ndmin=2)#likeatleast_2dbutalwaysmakes
acopy
array([[1]])
>>>mydescriptor={'names':('gender','age','weight'),'formats':
('S1','f4','f4')}#onewayofspecifyingthedatatype
>>>a=array([('M',64.0,75.0),('F',25.0,60.0)],
dtype=mydescriptor)#recarray
>>>printa
[('M',64.0,75.0)('F',25.0,60.0)]
>>>a['weight']
array([75.,60.],dtype=float32)
>>>a.dtype.names#Accesstotheorderedfieldnames
('gender','age','weight')
>>>mydescriptor=[('age',int16),('Nchildren',int8),
('weight',float32)]#anotherwayofspecifyingthedatatype
>>>a=array([(64,2,75.0),(25,0,60.0)],dtype=mydescriptor)
>>>a['Nchildren']
array([2,0],dtype=int8)
>>>mydescriptor=dtype([('x','f4'),('y','f4'),#nested
recarray
...('nested',[('i','i2'),('j','i2')])])
>>>array([(1.0,2.0,(1,2))],dtype=mydescriptor)#inputonerow
array([(1.0,2.0,(1,2))],
dtype=[('x','<f4'),('y','<f4'),('nested',[('i','<i2'),
('j','<i2')])])
>>>array([(1.0,2.0,(1,2)),(2.1,3.2,(3,2))],
dtype=mydescriptor)#inputtworows
array([(1.0,2.0,(1,2)),(2.0999999046325684,
3.2000000476837158,(3,2))],
dtype=[('x','<f4'),('y','<f4'),('nested',[('i','<i2'),
('j','<i2')])])
>>>a=array([(1.0,2.0,(1,2)),(2.1,3.2,(3,2))],
dtype=mydescriptor)#gettingsomecolumns
>>>a['x']#aplaincolumn
array([1.,2.0999999],dtype=float32)
>>>a['nested']#anestedcolumn
array([(1,2),(3,2)],
dtype=[('i','<i2'),('j','<i2')])
>>>a['nested']['i']#aplaincolumninsideanestedcolumn
>>>mydescriptor=dtype([('x','f4'),('y','f4'),#nested
recarray
...('nested',[('i','i2'),('j','i2')])])
>>>array([(1.0,2.0,(1,2))],dtype=mydescriptor)#inputonerow
array([(1.0,2.0,(1,2))],
dtype=[('x','<f4'),('y','<f4'),('nested',[('i','<i2'),
('j','<i2')])])
>>>array([(1.0,2.0,(1,2)),(2.1,3.2,(3,2))],
dtype=mydescriptor)#inputtworows
array([(1.0,2.0,(1,2)),(2.0999999046325684,
3.2000000476837158,(3,2))],
dtype=[('x','<f4'),('y','<f4'),('nested',[('i','<i2'),
('j','<i2')])])
>>>a=array([(1.0,2.0,(1,2)),(2.1,3.2,(3,2))],
dtype=mydescriptor)#gettingsomecolumns
>>>a['x']#aplaincolumn
array([1.,2.0999999],dtype=float32)
>>>a['nested']#anestedcolumn
array([(1,2),(3,2)],
dtype=[('i','<i2'),('j','<i2')])
>>>a['nested']['i']#aplaincolumninsideanestedcolumn
array([1,3],dtype=int16)
Seealso:dtype,mat,asarray
arrayrange()
Synonymforarange()
Seearange
array_split()
>>>fromnumpyimport*
>>>a=array([[1,2,3,4],[5,6,7,8]])
>>>array_split(a,2,axis=0)#splitain2parts.rowwise
[array([[1,2,3,4]]),array([[5,6,7,8]])]
>>>array_split(a,4,axis=1)#splitain4parts,columnwise
[array([[1],
[5]]),array([[2],
[6]]),array([[3],
[7]]),array([[4],
[8]])]
>>>array_split(a,3,axis=1)#impossibletosplitin3equal
parts>firstpart(s)arebigger
[array([[1,2],
[5,6]]),array([[3],
[7]]),array([[4],
[8]])]
>>>array_split(a,[2,3],axis=1)#makeasplitbeforethe2ndand
the3rdcolumn
[array([[1,2],
[5,6]]),array([[3],
[7]]),array([[4],
[8]])]
Seealso:dsplit,hsplit,vsplit,split,concatenate
asarray()
>>>fromnumpyimport*
>>>m=matrix('1258')
>>>m
matrix([[1,2],
[5,8]])
>>>a=asarray(m)#aisarraytypewithsamecontentsasm
dataisnotcopied
>>>a
array([[1,2],
[5,8]])
>>>m[0,0]=99
>>>m
matrix([[99,2],
[5,8]])
>>>a#nocopywasmade,somodifyingmmodifiesa,andvice
versa
array([[99,2],
[5,8]])
Seealso:asmatrix,array,matrix,mat
asanyarray()
>>>fromnumpyimport*
>>>a=array([[1,2],[5,8]])
>>>a
array([[1,2],
[5,8]])
>>>m=matrix('1258')
>>>m
matrix([[1,2],
[5,8]])
>>>asanyarray(a)#thearrayaisreturnedunmodified
array([[1,2],
[5,8]])
>>>asanyarray(m)#thematrixmisreturnedunmodified
matrix([[1,2],
[5,8]])
>>>asanyarray([1,2,3])#anewarrayisconstructedfromthelist
array([1,2,3])
Seealso:asmatrix,asarray,array,mat
asmatrix()
>>>fromnumpyimport*
>>>a=array([[1,2],[5,8]])
>>>a
array([[1,2],
[5,8]])
>>>m=asmatrix(a)#mismatrixtypewithsamecontentsasa
dataisnotcopied
>>>m
matrix([[1,2],
[5,8]])
>>>a[0,0]=99
>>>a
array([[99,2],
[5,8]])
>>>m#nocopywasmadesomodifyingamodifiesm,andviceversa
matrix([[99,2],
[5,8]])
Seealso:asarray,array,matrix,mat
astype()
>>>fromnumpyimport*
>>>x=array([1,2,3])
>>>y=x.astype(float64)#convertfromint32tofloat64
>>>type(y[0])
<type'numpy.float64'>
>>>x.astype(None)#Noneimpliesconvertingtothedefault
(float64)
array([1.,2.,3.])
Seealso:cast,dtype,ceil,floor,round_,fix
atleast_1d()
>>>fromnumpyimport*
>>>a=1#0darray
>>>b=array([2,3])#1darray
>>>c=array([[4,5],[6,7]])#2darray
>>>d=arange(8).reshape(2,2,2)#3darray
>>>d
array([[[0,1],
[2,3]],
[[4,5],
[6,7]]])
>>>atleast_1d(a,b,c,d)#alloutputarrayshavedim>=1
[array([1]),array([2,3]),array([[4,5],
[6,7]]),array([[[0,1],
[2,3]],
[[4,5],
[6,7]]])]
Seealso:atleast_2d,atleast_3d,newaxis,expand_dims
atleast_2d()
>>>fromnumpyimport*
>>>a=1#0darray
>>>b=array([2,3])#1darray
>>>c=array([[4,5],[6,7]])#2darray
>>>d=arange(8).reshape(2,2,2)#3darray
>>>d
array([[[0,1],
[2,3]],
[[4,5],
[6,7]]])
>>>atleast_2d(a,b,c,d)#alloutputarrayshavedim>=2
[array([[1]]),array([[2,3]]),array([[4,5],
[6,7]]),array([[[0,1],
[2,3]],
[[4,5],
[6,7]]])]
Seealso:atleast_1d,atleast_3d,newaxis,expand_dims
atleast_3d()
>>>fromnumpyimport*
>>>a=1#0darray
>>>b=array([2,3])#1darray
>>>c=array([[4,5],[6,7]])#2darray
>>>d=arange(8).reshape(2,2,2)#3darray
>>>d
array([[[0,1],
[2,3]],
[[4,5],
[6,7]]])
>>>atleast_3d(a,b,c,d)#alloutputarrayshavedim>=3
[array([[[1]]]),array([[[2],
[3]]]),array([[[4],
[5]],
[[6],
[7]]]),array([[[0,1],
[2,3]],
[[4,5],
[6,7]]])]
Seealso:atleast_1d,atleast_2d,newaxis,expand_dims
average()
>>>fromnumpyimport*
>>>a=array([1,2,3,4,5])
>>>w=array([0.1,0.2,0.5,0.2,0.2])#weights,not
necessarilynormalized
>>>average(a)#plainmeanvalue
3.0
>>>average(a,weights=w)#weightedaverage
3.1666666666666665
>>>average(a,weights=w,returned=True)#output=weighted
average,sumofweights
(3.1666666666666665,1.2)
Seealso:mean,median
beta()
>>>fromnumpyimport*
>>>fromnumpy.randomimport*
>>>beta(a=1,b=10,size=(2,2))#Betadistributionalpha=1,beta=10
array([[0.02571091,0.04973536],
[0.04887027,0.02382052]])
Seealso:seed
binary_repr()
>>>fromnumpyimport*
>>>a=25
>>>binary_repr(a)#binaryrepresentationof25
'11001'
>>>b=float_(pi)#numpyfloathasextrafunctionality...
>>>b.nbytes#...likethenumberofbytesittakes
8
>>>binary_repr(b.view('u8'))#viewfloatnumberasan8byte
integer,thengetbinarybitstring
'1010100010001000010110100011000'
bincount()
>>>fromnumpyimport*
>>>a=array([1,1,1,1,2,2,4,4,5,6,6,6])#doesn'tneedtobe
sorted
>>>bincount(a)#0occurs0times,1occurs4times,2occurs
twice,3occurs0times,...
array([0,4,2,0,2,1,3])
>>>a=array([5,4,4,2,2])
>>>w=array([0.1,0.2,0.1,0.3,0.5])
>>>bincount(a)#0&1don'toccur,2occurstwice,3doesn't
occur,4occurstwice,5once
array([0,0,2,0,2,1])
>>>bincount(a,weights=w)
array([0.,0.,0.8,0.,0.3,0.1])
>>>#0occurs0times>result[0]=0
>>>#1occurs0times>result[1]=0
>>>#2occursatindices3&4>result[2]=w[3]+w[4]
>>>#3occurs0times>result[3]=0
>>>#4occursatindices1&2>result[4]=w[1]+w[2]
>>>#5occursatindex0>result[5]=w[0]
Seealso:histogram,digitize
binomial()
>>>fromnumpyimport*
>>>fromnumpy.randomimport*
>>>binomial(n=100,p=0.5,size=(2,3))#binomialdistributionn
trials,p=successprobability
array([[38,50,53],
[56,48,54]])
>>>frompylabimport*#histogramplotexample
>>>hist(binomial(100,0.5,(1000)),20)
Seealso:random_sample,uniform,standard_normal,seed
bitwise_and()
>>>fromnumpyimport*
>>>bitwise_and(array([2,5,255]),array([4,4,4]))
array([0,4,4])
>>>bitwise_and(array([2,5,255,2147483647L],dtype=int32),
array([4,4,4,2147483647L],dtype=int32))
array([0,4,4,2147483647])
Seealso:bitwise_or,bitwise_xor,logical_and
bitwise_or()
>>>fromnumpyimport*
>>>bitwise_or(array([2,5,255]),array([4,4,4]))
array([6,5,255])
>>>bitwise_or(array([2,5,255,2147483647L],dtype=int32),
array([4,4,4,2147483647L],dtype=int32))
array([6,5,255,2147483647])
Seealso:bitwise_and,bitwise_xor,logical_or
bitwise_xor()
>>>fromnumpyimport*
>>>bitwise_xor(array([2,5,255]),array([4,4,4]))
array([6,1,251])
>>>bitwise_xor(array([2,5,255,2147483647L],dtype=int32),
array([4,4,4,2147483647L],dtype=int32))
array([6,1,251,0])
Seealso:bitwise_and,bitwise_or,logical_xor
bmat()
>>>fromnumpyimport*
>>>a=mat('1234')
>>>b=mat('5678')
>>>bmat('abba')#allelementsmustbeexistingsymbols
matrix([[1,2,5,6],
[3,4,7,8],
[5,6,1,2],
[7,8,3,4]])
Seealso:mat
broadcast()
>>>fromnumpyimport*
>>>a=array([[1,2],[3,4]])
>>>b=array([5,6])
>>>c=broadcast(a,b)
>>>c.nd#thenumberofdimensionsinthebroadcastedresult
2
>>>c.shape#theshapeofthebroadcastedresult
(2,2)
>>>c.size#totalsizeofthebroadcastedresult
4
>>>forvalueinc:printvalue
...
(1,5)
(2,6)
(3,5)
(4,6)
>>>c.reset()#resettheiteratortothebeginning
>>>c.next()#nextelement
(1,5)
Seealso:ndenumerate,ndindex,flat
bytes()
>>>fromnumpyimport*
>>>fromnumpy.randomimportbytes
>>>printrepr(bytes(5))#stringof5randombytes
'o\x07\x9f\xdf\xdf'
>>>printrepr(bytes(5))#anotherstringof5randombytes
'\x98\xc9KD\xe0'
Seealso:shuffle,permutation,seed
c_[]
>>>fromnumpyimport*
>>>c_[1:5]#forsingleranges,c_worksliker_
array([1,2,3,4])
>>>c_[1:5,2:6]#forcommaseparatedvalues,c_stackscolumn
wise
array([[1,2],
[2,3],
[3,4],
[4,5]])
>>>a=array([[1,2,3],[4,5,6]])
>>>c_[a,a]#concatenationalonglast(default)axis(column
wise,that'swhyit'scalledc_)
array([[1,2,3,1,2,3],
[4,5,6,4,5,6]])
>>>c_['0',a,a]#concatenationalong1staxis,equivalentto
r_[a,a]
array([[1,2,3],
[4,5,6],
[1,2,3],
[4,5,6]])
Seealso:r_,hstack,vstack,column_stack,concatenate,bmat,s_
cast[]()
>>>fromnumpyimport*
>>>x=arange(3)
>>>x.dtype
dtype('int32')
>>>cast['int64'](x)
array([0,1,2],dtype=int64)
>>>cast['uint'](x)
array([0,1,2],dtype=uint32)
>>>cast[float128](x)
array([0.0,1.0,2.0],dtype=float128)
>>>cast.keys()#listdtypecastpossibilities
<snip>
Seealso:astype,typeDict
ceil()
>>>fromnumpyimport*
>>>a=array([1.7,1.5,0.2,0.2,1.5,1.7])
>>>ceil(a)#nearestintegersgreaterthanorequaltoa
array([1.,1.,0.,1.,2.,2.])
Seealso:floor,round_,fix,astype
choose()
>>>fromnumpyimport*
>>>choice0=array([10,12,14,16])#selectorandchoicearrays
mustbeequallysized
>>>choice1=array([20,22,24,26])
>>>choice2=array([30,32,34,36])
>>>selector=array([0,0,2,1])#selectorcanonlycontain
integersinrange(number_of_choice_arrays)
>>>selector.choose(choice0,choice1,choice2)
array([10,12,34,26])
>>>a=arange(4)
>>>choose(a>=2,(choice0,choice1))#separatefunctionalso
exists
array([10,12,24,26])
Seealso:compress,take,where,select
clip()
>>>fromnumpyimport*
>>>a=array([5,15,25,3,13])
>>>a.clip(min=10,max=20)
array([10,15,20,10,13])
>>>clip(a,10,20)#thissyntaxalsoexists
Seealso:wherecompress
column_stack()
>>>fromnumpyimport*
>>>a=array([1,2])
>>>b=array([3,4])
>>>c=array([5,6])
>>>column_stack((a,b,c))#a,b,care1darrayswithequallength
array([[1,3,5],
[2,4,6]])
Seealso:concatenate,dstack,hstack,vstack,c_
compress()
>>>fromnumpyimport*
>>>a=array([10,20,30,40])
>>>condition=(a>15)&(a<35)
>>>condition
array([False,True,True,False],dtype=bool)
>>>a.compress(condition)
array([20,30])
>>>a[condition]#sameeffect
array([20,30])
>>>compress(a>=30,a)#thisformalsoexists
array([30,40])
>>>b=array([[10,20,30],[40,50,60]])
>>>b.compress(b.ravel()>=22)
array([30,40,50,60])
>>>x=array([3,1,2])
>>>y=array([50,101])
>>>b.compress(x>=2,axis=1)#illustratestheuseoftheaxis
keyword
array([[10,30],
[40,60]])
>>>b.compress(y>=100,axis=0)
array([[40,50,60]])
Seealso:choose,take,where,trim_zeros,unique,unique1d
concatenate()
>>>fromnumpyimport*
>>>x=array([[1,2],[3,4]])
>>>y=array([[5,6],[7,8]])
>>>concatenate((x,y))#defaultisaxis=0
array([[1,2],
[3,4],
[5,6],
[7,8]])
>>>concatenate((x,y),axis=1)
array([[1,2,5,6],
[3,4,7,8]])
Seealso:append,column_stack,dstack,hstack,vstack,array_split
conj()
Synonymforconjugate()
Seeconjugate()
conjugate()
>>>a=array([1+2j,34j])
>>>a.conj()#.conj()and.conjugate()arethesame
array([1.2.j,3.+4.j])
>>>a.conjugate()
array([1.2.j,3.+4.j])
>>>conj(a)#isalsopossible
>>>conjugate(a)#isalsopossible
Seealso:vdot
copy()
>>>fromnumpyimport*
>>>a=array([1,2,3])
>>>a
array([1,2,3])
>>>b=a#bisareferencetoa
>>>b[1]=4
>>>a
array([1,4,3])
>>>a=array([1,2,3])
>>>b=a.copy()#bisnowanindependentcopyofa
>>>b[1]=4
>>>a
array([1,2,3])
>>>b
array([1,4,3])
Seealso:view
corrcoef()
>>>fromnumpyimport*
>>>T=array([1.3,4.5,2.8,3.9])#temperaturemeasurements
>>>P=array([2.7,8.7,4.7,8.2])#correspondingpressure
measurements
>>>printcorrcoef([T,P])#correlationmatrixoftemperatureand
pressure
[[1.0.98062258]
[0.980622581.]]
>>>rho=array([8.5,5.2,6.9,6.5])#correspondingdensity
measurements
>>>data=column_stack([T,P,rho])
>>>printcorrcoef([T,P,rho])#correlationmatrixofT,Pandrho
[[1.0.980622580.97090288]
[0.980622581.0.91538464]
[0.970902880.915384641.]]
Seealso:cov,var
cos()
>>>cos(array([0,pi/2,pi]))
array([1.00000000e+00,6.12303177e17,1.00000000e+00])
cov()
>>>fromnumpyimport*
>>>x=array([1.,3.,8.,9.])
>>>variance=cov(x)#normalizedbyN1
>>>variance=cov(x,bias=1)#normalizedbyN
>>>T=array([1.3,4.5,2.8,3.9])#temperaturemeasurements
>>>P=array([2.7,8.7,4.7,8.2])#correspondingpressure
measurements
>>>cov(T,P)#covariancebetweentemperatureandpressure
3.9541666666666657
>>>rho=array([8.5,5.2,6.9,6.5])#correspondingdensity
measurements
>>>data=column_stack([T,P,rho])
>>>printcov(data)#covariancematrixofT,Pandrho
[[1.975833333.954166671.85583333]
[3.954166678.229166673.57083333]
[1.855833333.570833331.84916667]]
Seealso:corrcoef,std,var
cross()
>>>fromnumpyimport*
>>>x=array([1,2,3])
>>>y=array([4,5,6])
>>>cross(x,y)#vectorcrossproduct
array([3,6,3])
Seealso:inner,ix_,outer
cumprod()
>>>fromnumpyimport*
>>>a=array([1,2,3])
>>>a.cumprod()#totalproduct1*2*3=6,andintermediate
results1,1*2
array([1,2,6])
>>>cumprod(a)#alsoexists
array([1,2,6])
>>>a=array([[1,2,3],[4,5,6]])
>>>a.cumprod(dtype=float)#specifytypeofoutput
array([1.,2.,6.,24.,120.,720.])
>>>a.cumprod(axis=0)#foreachofthe3columns:productand
intermediateresults
array([[1,2,3],
[4,10,18]])
>>>a.cumprod(axis=1)#foreachofthetworows:productand
intermediateresults
array([[1,2,6],
[4,20,120]])
Seealso:accumulate,prod,cumsum
cumsum()
>>>fromnumpyimport*
>>>a=array([1,2,3])#cumulativesum=intermediatesumming
results&totalsum
>>>a.cumsum()
array([1,3,6])
>>>cumsum(a)#alsoexists
array([1,3,6])
>>>a=array([[1,2,3],[4,5,6]])
>>>a.cumsum(dtype=float)#specifiestypeofoutputvalue(s)
array([1.,3.,6.,10.,15.,21.])
>>>a.cumsum(axis=0)#sumoverrowsforeachofthe3columns
array([[1,2,3],
[5,7,9]])
>>>a.cumsum(axis=1)#sumovercolumnsforeachofthe2rows
array([[1,3,6],
[4,9,15]])
Seealso:accumulate,sum,cumprod
delete()
>>>fromnumpyimport*
>>>a=array([0,10,20,30,40])
>>>delete(a,[2,4])#removea[2]anda[4]
array([0,10,30])
>>>a=arange(16).reshape(4,4)
>>>a
array([[0,1,2,3],
[4,5,6,7],
[8,9,10,11],
[12,13,14,15]])
>>>delete(a,s_[1:3],axis=0)#removerows1and2
array([[0,1,2,3],
[12,13,14,15]])
>>>delete(a,s_[1:3],axis=1)#removecolumns1and2
array([[0,3],
[4,7],
[8,11],
[12,15]])
Seealso:append,insert
det()
>>>fromnumpyimport*
>>>fromnumpy.linalgimportdet
>>>A=array([[1.,2.],[3.,4.]])
>>>det(A)#determinantofsquarematrix
2.0
Seealso:inv
diag()
>>>fromnumpyimport*
>>>a=arange(12).reshape(4,3)
>>>printa
[[012]
[345]
[678]
[91011]]
>>>printdiag(a,k=0)
[048]
>>>printdiag(a,k=1)
[15]
>>>printdiag(array([1,4,5]),k=0)
[[100]
[040]
[005]]
>>>printdiag(array([1,4,5]),k=1)
[[0100]
[0040]
[0005]
[0000]]
Seealso:diagonal,diagflat,trace
diagflat()
>>>fromnumpyimport*
>>>x=array([[5,6],[7,8]])
>>>diagflat(x)#flattenx,thenputelementsondiagonal
array([[5,0,0,0],
[0,6,0,0],
[0,0,7,0],
[0,0,0,8]])
Seealso:diag,diagonal,flatten
diagonal()
>>>fromnumpyimport*
>>>a=arange(12).reshape(3,4)
>>>printa
[[0123]
[4567]
[891011]]
>>>a.diagonal()
array([0,5,10])
>>>a.diagonal(offset=1)
array([1,6,11])
>>>diagonal(a)#Alsothisformexists
array([0,5,10])
Seealso:diag,diagflat,trace
diff()
>>>fromnumpyimport*
>>>x=array([0,1,3,9,5,10])
>>>diff(x)#1storderdifferencesbetweentheelementsofx
array([1,2,6,4,5])
>>>diff(x,n=2)#2ndorderdifferences,equivalentto
diff(diff(x))
array([1,4,10,9])
>>>x=array([[1,3,6,10],[0,5,6,8]])
>>>diff(x)#1storderdifferencesbetweenthecolumns(default:
axis=1)
array([[2,3,4],
[5,1,2]])
>>>diff(x,axis=0)#1storderdifferencebetweentherows
array([[1,2,0,2]])
digitize()
>>>fromnumpyimport*
>>>x=array([0.2,6.4,3.0,1.6])
>>>bins=array([0.0,1.0,2.5,4.0,10.0])#monotonically
increasing
>>>d=digitize(x,bins)#inwhichbinfallseachvalueofx?
>>>d
array([1,4,3,2])
>>>forninrange(len(x)):
...printbins[d[n]1],"<=",x[n],"<",bins[d[n]]
...
0.0<=0.2<1.0
4.0<=6.4<10.0
2.5<=3.0<4.0
1.0<=1.6<2.5
Seealso:bincount,histogram
dot()
>>>fromnumpyimport*
>>>x=array([[1,2,3],[4,5,6]])
>>>x.shape
(2,3)
>>>y=array([[1,2],[3,4],[5,6]])
>>>y.shape
(3,2)
>>>dot(x,y)#matrixmultiplication(2,3)x(3,2)>(2,2)
array([[22,28],
[49,64]])
>>>
>>>importnumpy
>>>ifid(dot)==id(numpy.core.multiarray.dot):#Awaytoknow
ifyouusefastblas/lapackornot.
...print"Notusingblas/lapack!"
Seealso:vdot,inner,multiply
dsplit()
>>>fromnumpyimport*
>>>a=array([[1,2],[3,4]])
>>>b=dstack((a,a,a,a))
>>>b.shape#stackingindepth:forkin(0,..,3):b[:,:,k]=a
(2,2,4)
>>>c=dsplit(b,2)#split,depthwise,in2equalparts
>>>printc[0].shape,c[1].shape#forkin(0,1):c[0][:,:,k]=a
andc[1][:,:,k]=a
(2,2,2)(2,2,2)
>>>d=dsplit(b,[1,2])#splitbefore[:,:,1]andbefore[:,:,2]
>>>printd[0].shape,d[1].shape,d[2].shape#foranyofthe
parts:d[.][:,:,k]=a
(2,2,1)(2,2,1)(2,2,2)
Seealso:split,array_split,hsplit,vsplit,dstack
dstack()
>>>fromnumpyimport*
>>>a=array([[1,2],[3,4]])#shapesofaandbcanonlydiffer
inthe3rddimension(ifpresent)
>>>b=array([[5,6],[7,8]])
>>>dstack((a,b))#stackarraysalongathirdaxis(depthwise)
array([[[1,5],
[2,6]],
[[3,7],
[4,8]]])
Seealso:column_stack,concatenate,hstack,vstack,dsplit
dtype()
>>>fromnumpyimport*
>>>dtype('int16')#usingarrayscalartype
dtype('int16')
>>>dtype([('f1','int16')])#record,1fieldnamed'f1',
containingint16
dtype([('f1','<i2')])
>>>dtype([('f1',[('f1','int16')])])#record,1fieldnamed
'f1'containingarecordthathas1field.
dtype([('f1',[('f1','<i2')])])
>>>dtype([('f1','uint'),('f2','int32')])#recordwith2
fields:field1containsanunsignedint,2ndfieldanint32
dtype([('f1','<u4'),('f2','<i4')])
>>>dtype([('a','f8'),('b','S10')])#usingarrayprotocoltype
strings
dtype([('a','<f8'),('b','|S10')])
>>>dtype("i4,(2,3)f8")#usingcommaseparatedfieldformats.
(2,3)istheshape
dtype([('f0','<i4'),('f1','<f8',(2,3))])
>>>dtype([('hello',('int',3)),('world','void',10)])#using
tuples.intisfixedtype:3isshapevoidisflextype:10is
size.
dtype([('hello','<i4',3),('world','|V10')])
>>>dtype(('int16',{'x':('int8',0),'y':('int8',1)}))#subdivide
int16in2int8,calledxandy.0and1aretheoffsetsinbytes
dtype(('<i2',[('x','|i1'),('y','|i1')]))
>>>dtype({'names':['gender','age'],'formats':['S1',uint8]})#
usingdictionaries.2fieldsnamed'gender'and'age'
dtype([('gender','|S1'),('age','|u1')])
>>>dtype({'surname':('S25',0),'age':(uint8,25)})#0and25are
offsetsinbytes
dtype([('surname','|S25'),('age','|u1')])
>>>
>>>a=dtype('int32')
>>>a
dtype('int32')
>>>a.type#typeobject
<type'numpy.int32'>
>>>a.kind#charactercode(oneof'biufcSUV')toidentify
generaltype
'i'
>>>a.char#uniquecharcodeofeachofthe21builtintypes
'l'
>>>a.num#uniquenumberofeachofthe21builtintypes
7
>>>a.str#arrayprotocoltypestring
'<i4'
>>>a.name#nameofthisdatatype
'int32'
>>>a.byteorder#'=':native,'<':littleendian,'>':bigendian,
'|':notapplicable
'='
>>>a.itemsize#itemsizeinbytes
4
>>>a=dtype({'surname':('S25',0),'age':(uint8,25)})
>>>a.fields.keys()
['age','surname']
>>>a.fields.values()
[(dtype('uint8'),25),(dtype('|S25'),0)]
>>>a=dtype([('x','f4'),('y','f4'),#nestedfield
...('nested',[('i','i2'),('j','i2')])])
>>>a.fields['nested']#accessnestedfields
(dtype([('i','<i2'),('j','<i2')]),8)
>>>a.fields['nested'][0].fields['i']#accessnestedfields
(dtype('int16'),0)
>>>a.fields['nested'][0].fields['i'][0].type
<type'numpy.int16'>
Seealso:array,typeDict,astype
empty()
>>>fromnumpyimport*
>>>empty(3)#uninitializedarray,size=3,dtype=float
array([6.08581638e+000,3.45845952e323,4.94065646e324])
>>>empty((2,3),int)#uninitializedarray,dtype=int
array([[1075337192,1075337192,135609024],
[1084062604,1197436517,1129066306]])
Seealso:ones,zeros,eye,identity
empty_like()
>>>fromnumpyimport*
>>>a=array([[1,2,3],[4,5,6]])
>>>empty_like(a)#uninitializedarraywiththesameshapeand
datatypeas'a'
array([[0,25362433,6571520],
[21248,136447968,4]])
Seealso:ones_like,zeros_like
expand_dims()
>>>fromnumpyimport*
>>>x=array([1,2])
>>>expand_dims(x,axis=0)#Equivalenttox[newaxis,:]orx[None]
orx[newaxis]
array([[1,2]])
>>>expand_dims(x,axis=1)#Equivalenttox[:,newaxis]
array([[1],
[2]])
Seealso:newaxis,atleast_1d,atleast_2d,atleast_3d
eye()
>>>fromnumpyimport*
>>>eye(3,4,0,dtype=float)#a3x4matrixcontainingzerosexcept
forthe0thdiagonalthatcontainsones
array([[1.,0.,0.,0.],
[0.,1.,0.,0.],
[0.,0.,1.,0.]])
>>>eye(3,4,1,dtype=float)#a3x4matrixcontainingzerosexcept
forthe1stdiagonalthatcontainsones
array([[0.,1.,0.,0.],
[0.,0.,1.,0.],
[0.,0.,0.,1.]])
Seealso:ones,zeros,empty,identity
fft()
>>>fromnumpyimport*
>>>fromnumpy.fftimport*
>>>signal=array([2.,8.,6.,4.,1.,0.,3.,5.])#could
alsobecomplex
>>>fourier=fft(signal)
>>>fourier
array([13.+0.j,3.36396103+4.05025253j,
2.+1.j,9.3639610313.94974747j,
21.+0.j,9.36396103+13.94974747j,
2.1.j,3.363961034.05025253j])
>>>
>>>N=len(signal)
>>>fourier=empty(N,complex)
>>>forkinrange(N):#equivalentbutmuchslower
...fourier[k]=sum(signal*exp(1j*2*pi*k*arange(N)/N))
...
>>>timestep=0.1#ifunit=day>frequnit=cycles/day
>>>fftfreq(N,d=timestep)#freqscorrespondingto'fourier'
array([0.,1.25,2.5,3.75,5.,3.75,2.5,1.25])
Seealso:ifft,fftfreq,fftshift
fftfreq()
>>>fromnumpyimport*
>>>fromnumpy.fftimport*
>>>signal=array([2.,8.,6.,4.,1.,0.,3.,5.])
>>>fourier=fft(signal)
>>>N=len(signal)
>>>timestep=0.1#ifunit=day>frequnit=cycles/day
>>>freq=fftfreq(N,d=timestep)#freqscorrespondingto
'fourier'
>>>freq
array([0.,1.25,2.5,3.75,5.,3.75,2.5,1.25])
>>>
>>>fftshift(freq)#freqsinascendingorder
array([5.,3.75,2.5,1.25,0.,1.25,2.5,3.75])
Seealso:fft,ifft,fftshift
fftshift()
>>>fromnumpyimport*
>>>fromnumpy.fftimport*
>>>signal=array([2.,8.,6.,4.,1.,0.,3.,5.])
>>>fourier=fft(signal)
>>>N=len(signal)
>>>timestep=0.1#ifunit=day>frequnit=cycles/day
>>>freq=fftfreq(N,d=timestep)#freqscorrespondingto
'fourier'
>>>freq
array([0.,1.25,2.5,3.75,5.,3.75,2.5,1.25])
>>>
>>>freq=fftshift(freq)#freqsinascendingorder
>>>freq
array([5.,3.75,2.5,1.25,0.,1.25,2.5,3.75])
>>>fourier=fftshift(fourier)#adjustfouriertonewfreqorder
>>>
>>>freq=ifftshift(freq)#undopreviousfrequencyshift
>>>fourier=ifftshift(fourier)#undopreviousfouriershift
Seealso:fft,ifft,fftfreq
fill()
>>>fromnumpyimport*
>>>a=arange(4,dtype=int)
>>>a
array([0,1,2,3])
>>>a.fill(7)#replaceallelementswiththenumber7
>>>a
array([7,7,7,7])
>>>a.fill(6.5)#fillvalueisconvertedtodtypeofa
>>>a
array([6,6,6,6])
Seealso:empty,zeros,ones,repeat
finfo()
>>>fromnumpyimport*
>>>f=finfo(float)#thenumbersgivenaremachinedependent
>>>f.nmant,f.nexp#nrofbitsinthemantissaandinthe
exponent
(52,11)
>>>f.machep#mostnegativensothat1.0+2**n!=1.0
52
>>>f.eps#floatingpointprecision:2**machep
array(2.2204460492503131e16)
>>>f.precision#nrofprecisedecimaldigits:int(log10(eps))
15
>>>f.resolution#10**(precision)
array(1.0000000000000001e15)
>>>f.negep#mostnegativensothat1.02**n!=1.0
53
>>>f.epsneg#floatingpointprecision:2**negep
array(1.1102230246251565e16)
>>>f.minexp#mostnegativensothat2**ngivesnormalnumbers
1022
>>>f.tiny#smallestusuablefloatingpointnr:2**minexp
array(2.2250738585072014e308)
>>>f.maxexp#smallestpositivensothat2**ncausesoverflow
1024
>>>f.min,f.max#themostnegativeandmostpositiveusuable
floatingnumber
(1.7976931348623157e+308,array(1.7976931348623157e+308))
fix()
>>>fromnumpyimport*
>>>a=array([1.7,1.5,0.2,0.2,1.5,1.7])
>>>fix(a)#roundatonearestintegertowardszero
array([1.,1.,0.,0.,1.,1.])
Seealso:round_,ceil,floor,astype
flat
>>>fromnumpyimport*
>>>a=array([[10,30],[40,60]])
>>>iter=a.flat#.flatreturnsaniterator
>>>iter.next()#cyclethrougharraywith.next()
10
>>>iter.next()
30
>>>iter.next()
40
Seealso:broadcast,flatten
flatten()
>>>fromnumpyimport*
>>>a=array([[[1,2]],[[3,4]]])
>>>printa
[[[12]]
[[34]]]
>>>b=a.flatten()#bisnowa1dversionofa,anewarray,
notareference
>>>printb
[1234]
Seealso:ravel,flat
fliplr()
>>>fromnumpyimport*
>>>a=arange(12).reshape(4,3)
>>>a
array([[0,1,2],
[3,4,5],
[6,7,8],
[9,10,11]])
>>>fliplr(a)#flipleftright
array([[2,1,0],
[5,4,3],
[8,7,6],
[11,10,9]])
Seealso:flipud,rot90
flipud()
>>>fromnumpyimport*
>>>a=arange(12).reshape(4,3)
>>>a
array([[0,1,2],
[3,4,5],
[6,7,8],
[9,10,11]])
>>>flipud(a)#flipupdown
array([[9,10,11],
[6,7,8],
[3,4,5],
[0,1,2]])
Seealso:fliplr,rot90
floor()
>>>fromnumpyimport*
>>>a=array([1.7,1.5,0.2,0.2,1.5,1.7])
>>>floor(a)
array([2.,2.,1.,0.,1.,1.])#nearestintegersmallerthan
orequaltoa#nearestintegersgreaterthanorequaltoa
Seealso:ceil,round_,fix,astype
fromarrays()
>>>fromnumpyimport*
>>>x=array(['Smith','Johnson','McDonald'])#datatypeisstring
>>>y=array(['F','F','M'],dtype='S1')#datatypeisasingle
character
>>>z=array([20,25,23])#datatypeisinteger
>>>data=rec.fromarrays([x,y,z],names='surname,gender,age')#
converttorecordarray
>>>data[0]
('Smith','F',20)
>>>data.age#namesareavailableasattributes
array([20,25,23])
Seealso:view
frombuffer()
>>>fromnumpyimport*
>>>buffer="\x00\x00\x00\x00\x00\x00\xf0?
\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x08\
...
@\x00\x00\x00\x00\x00\x00\x10@\x00\x00\x00\x00\x00\x00\x14@\x00\x0
0\x00\x00\x00\x00\x18@"
>>>a=frombuffer(buffer,complex128)
>>>a
array([1.+2.j,3.+4.j,5.+6.j])
Seealso:fromfunction,fromfile
fromfile()
>>>fromnumpyimport*
>>>y=array([2.,4.,6.,8.])
>>>y.tofile("myfile.dat")#binaryformat
>>>y.tofile("myfile.txt",sep='\n',format="%e")#ascii
format,onecolumn,exponentialnotation
>>>fromfile('myfile.dat',dtype=float)
array([2.,4.,6.,8.])
>>>fromfile('myfile.txt',dtype=float,sep='\n')
array([2.,4.,6.,8.])
Seealso:loadtxt,fromfunction,tofile,frombuffer,savetxt
fromfunction()
>>>fromnumpyimport*
>>>deff(i,j):
...returni**2+j**2
...
>>>fromfunction(f,(3,3))#evaluatefunctiomforall
combinationsofindices[0,1,2]x[0,1,2]
array([[0,1,4],
[1,2,5],
[4,5,8]])
Seealso:fromfile,frombuffer
fromiter()
>>>fromnumpyimport*
>>>importitertools
>>>mydata=[[55.5,40],[60.5,70]]#Listoflists
>>>mydescriptor={'names':('weight','age'),'formats':
(float32,int32)}#Descriptorofthedata
>>>myiterator=itertools.imap(tuple,mydata)#Cleverwayof
puttinglistoflistsintoiterator
#oftuples.E.g.:myiterator.next()==(55.5,40.)
>>>a=fromiter(myiterator,dtype=mydescriptor)
>>>a
array([(55.5,40),(60.5,70)],
dtype=[('weight','<f4'),('age','<i4')])
Seealso:fromarrays,frombuffer,fromfile,fromfunction
generic
>>>fromnumpyimport*
>>>numpyscalar=string_('7')#Converttonumpyscalar
>>>numpyscalar#Lookslikeabuildinscalar...
'7'
>>>type(numpyscalar)#...butitisn't
<type'numpy.string_'>
>>>buildinscalar='7'#Buildinpythonscalar
>>>type(buildinscalar)
<type'str'>
>>>isinstance(numpyscalar,generic)#CheckifscalarisaNumPy
one
True
>>>isinstance(buildinscalar,generic)#Exampleonhowto
recognizeNumPyscalars
False
gumbel()
>>>fromnumpyimport*
>>>fromnumpy.randomimport*
>>>gumbel(loc=0.0,scale=1.0,size=(2,3))#Gumbeldistribution
location=0.0,scale=1.0
array([[1.25923601,1.68758144,1.76620507],
[1.96820048,0.21219499,1.83579566]])
>>>frompylabimport*#histogramplotexample
>>>hist(gumbel(0,1,(1000)),50)
Seealso:random_sample,uniform,poisson,seed
histogram()
>>>fromnumpyimport*
>>>x=array([0.2,6.4,3.0,1.6,0.9,2.3,1.6,5.7,8.5,4.0,
12.8])
>>>bins=array([0.0,1.0,2.5,4.0,10.0])#increasing
monotonically
>>>N,bins=histogram(x,bins)
>>>N,bins
(array([2,3,1,4]),array([0.,1.,2.5,4.,10.]))
>>>forninrange(len(bins)1):
...print"#",N[n],"numberfallintobin[",bins[n],",",
bins[n+1],"["
...
#2numbersfallintobin[0.0,1.0[
#3numbersfallintobin[1.0,2.5[
#1numbersfallintobin[2.5,4.0[
#4numbersfallintobin[4.0,10.0[
#
>>>N,bins=histogram(x,5,range=(0.0,10.0))#5binboundaries
intherange(0,10)
>>>N,bins
(array([4,2,2,1,2]),array([0.,2.,4.,6.,8.]))
>>>N,bins=histogram(x,5,range=(0.0,10.0),normed=True)#
normalizehistogram,i.e.dividebylen(x)
>>>N,bins
(array([0.18181818,0.09090909,0.09090909,0.04545455,
0.09090909]),array([0.,2.,4.,6.,8.]))
Seealso:bincount,digitize
hsplit()
>>>fromnumpyimport*
>>>a=array([[1,2,3,4],[5,6,7,8]])
>>>hsplit(a,2)#split,columnwise,in2equalparts
[array([[1,2],
[5,6]]),array([[3,4],
[7,8]])]
>>>hsplit(a,[1,2])#splitbeforecolumn1andbeforecolumn2
[array([[1],
[5]]),array([[2],
[6]]),array([[3,4],
[7,8]])]
Seealso:split,array_split,dsplit,vsplit,hstack
hstack()
>>>fromnumpyimport*
>>>a=array([[1],[2]])#2x1array
>>>b=array([[3,4],[5,6]])#2x2array
>>>hstack((a,b,a))#onlythe2nddimensionofthearraysis
allowedtobedifferent
array([[1,3,4,1],
[2,5,6,2]])
Seealso:column_stack,concatenate,dstack,vstack,hsplit
hypot()
>>>fromnumpyimport*
>>>hypot(3.,4.)#hypotenuse:sqrt(3**2+4**2)=5
5.0
>>>z=array([2+3j,3+4j])
>>>hypot(z.real,z.imag)#normofcomplexnumbers
array([3.60555128,5.])
Seealso:angle,abs
identity()
>>>fromnumpyimport*
>>>identity(3,float)
array([[1.,0.,0.],
[0.,1.,0.],
[0.,0.,1.]])
Seealso:empty,eye,ones,zeros
ifft()
>>>fromnumpyimport*
>>>fromnumpy.fftimport*
>>>signal=array([2.,8.,6.,4.,1.,0.,3.,5.])
>>>fourier=fft(signal)
>>>ifft(fourier)#Inversefouriertransform
array([2.+0.00000000e+00j,8.+1.51410866e15j,6.
+3.77475828e15j,
4.+2.06737026e16j,1.+0.00000000e+00j,0.1.92758271e
15j,
3.3.77475828e15j,5.+2.06737026e16j])
>>>
>>>allclose(signal.astype(complex),ifft(fft(signal)))#
ifft(fft())=originalsignal
True
>>>
>>>N=len(fourier)
>>>signal=empty(N,complex)
>>>forkinrange(N):#equivalentbutmuchslower
...signal[k]=sum(fourier*exp(+1j*2*pi*k*arange(N)/N))/N
Seealso:fft,fftfreq,fftshift
imag
>>>fromnumpyimport*
>>>a=array([1+2j,3+4j,5+6j])
>>>a.imag
array([2.,4.,6.])
>>>a.imag=9
>>>a
array([1.+9.j,3.+9.j,5.+9.j])
>>>a.imag=array([9,8,7])
>>>a
array([1.+9.j,3.+8.j,5.+7.j])
Seealso:real,angle
index_exp[]
>>>fromnumpyimport*
>>>myslice=index_exp[2:4,...,4,::1]#myslicecouldnowbe
passedtoafunction,forexample.
>>>printmyslice
(slice(2,4,None),Ellipsis,4,slice(None,None,1))
Seealso:slice,s_
indices()
>>>fromnumpyimport*
>>>indices((2,3))
array([[[0,0,0],
[1,1,1]],
[[0,1,2],
[0,1,2]]])
>>>a=array([[0,1,2,3,4],
...[10,11,12,13,14],
...[20,21,22,23,24],
...[30,31,32,33,34]])
>>>i,j=indices((2,3))
>>>a[i,j]
array([[0,1,2],
[10,11,12]])
Seealso:mgrid,[],ix_,slice
inf
>>>fromnumpyimport*
>>>exp(array([1000.]))#inf=infinite=numbertoolargeto
represent,machinedependent
array([inf])
>>>x=array([2,inf,1,inf])
>>>isfinite(x)#showwhichelementsarenotnan/inf/inf
array([True,False,True,False],dtype=bool)
>>>isinf(x)#showwhichelementsareinf/inf
array([False,True,False,True],dtype=bool)
>>>isposinf(x)#showwhichelementsareinf
array([False,False,False,True],dtype=bool)
>>>isneginf(x)#showwhichelementsareinf
array([False,True,False,False],dtype=bool)
>>>nan_to_num(x)#replaceinf/infwithmostnegative/positive
representablenumber
array([2.00000000e+000,1.79769313e+308,1.00000000e+000,
1.79769313e+308])
Seealso:nan,finfo
inner()
>>>fromnumpyimport*
>>>x=array([1,2,3])
>>>y=array([10,20,30])
>>>inner(x,y)#1x10+2x20+3x30=140
140
Seealso:cross,outer,dot
insert()
>>>fromnumpyimport*
>>>a=array([10,20,30,40])
>>>insert(a,[1,3],50)#insertvalue50beforeelements[1]and
[3]
array([10,50,20,30,50,40])
>>>insert(a,[1,3],[50,60])#insertvalue50beforeelement[1]
andvalue60beforeelement[3]
array([10,50,20,30,60,40])
>>>a=array([[10,20,30],[40,50,60],[70,80,90]])
>>>insert(a,[1,2],100,axis=0)#insertrowwithvalues100
beforerow[1]andbeforerow[2]
array([[10,20,30],
[100,100,100],
[40,50,60],
[100,100,100],
[70,80,90]])
>>>insert(a,[0,1],[[100],[200]],axis=0)
array([[100,100,100],
[10,20,30],
[200,200,200],
[40,50,60],
[70,80,90]])
>>>insert(a,[0,1],[100,200],axis=1)
array([[100,10,200,20,30],
[100,40,200,50,60],
[100,70,200,80,90]])
Seealso:delete,append
inv()
>>>fromnumpyimport*
>>>fromnumpy.linalgimportinv
>>>a=array([[3,1,5],[1,0,8],[2,1,4]])
>>>printa
[[315]
[108]
[214]]
>>>inva=inv(a)#Inversematrix
>>>printinva
[[1.142857140.142857141.14285714]
[1.714285710.285714292.71428571]
[0.142857140.142857140.14285714]]
>>>dot(a,inva)#Checktheresult,shouldbeeye(3)within
machineprecision
array([[1.00000000e00,2.77555756e17,3.60822483e16],
[0.00000000e+00,1.00000000e+00,0.00000000e+00],
[1.11022302e16,0.00000000e+00,1.00000000e+00]])
Seealso:solve,pinv,det
iscomplex()
>>>importnumpyasnp
>>>a=np.array([1,2,3.j])
>>>np.iscomplex(a)
array([False,False,True],dtype=bool)
iscomplexobj()
>>>importnumpyasnp
>>>a=np.array([1,2,3.j])
>>>np.iscomplexobj(a)
True
>>>a=np.array([1,2,3])
>>>np.iscomplexobj(a)
False
>>>a=np.array([1,2,3],dtype=np.complex)
>>>np.iscomplexobj(a)
True
item()
>>>fromnumpyimport*
>>>a=array([5])
>>>type(a[0])
<type'numpy.int32'>
>>>a.item()#Conversionofarrayofsize1toPythonscalar
5
>>>type(a.item())
<type'int'>
>>>b=array([2,3,4])
>>>b[1].item()#Conversionof2ndelementtoPythonscalar
3
>>>type(b[1].item())
<type'int'>
>>>b.item(2)#Return3rdelementconvertedtoPythonscalar
4
>>>type(b.item(2))
<type'int'>
>>>type(b[2])#b[2]isslowerthanb.item(2),andthereisno
conversion
<type'numpy.int32'>
Seealso:[]
ix_()
>>>fromnumpyimport*
>>>a=arange(9).reshape(3,3)
>>>printa
[[012]
[345]
[678]]
>>>indices=ix_([0,1,2],[1,2,0])#tricktobeusedwitharray
broadcasting
>>>printindices
(array([[0],
[1],
[2]]),array([[1,2,0]]))
>>>printa[indices]
[[120]
[453]
[786]]
>>>#Thelatterarrayisthecrossproduct:
>>>#[[a[0,1]a[0,2]a[0,0]]
...#[a[1,1]a[1,2]a[1,0]]
...#[a[2,1]a[2,2]a[2,0]]]
...
Seealso:[],indices,cross,outer
lexsort()
>>>fromnumpyimport*
>>>serialnr=array([1023,5202,6230,1671,1682,5241])
>>>height=array([40.,42.,60.,60.,98.,40.])
>>>width=array([50.,20.,70.,60.,15.,30.])
>>>
>>>#Wewanttosorttheserialnumberswithincreasingheight,
_AND_
>>>#serialnumberswithequalheightsshouldbesortedwith
increasingwidth.
>>>
>>>indices=lexsort(keys=(width,height))#mindtheorder!
>>>indices
array([5,0,1,3,2,4])
>>>forninindices:
...printserialnr[n],height[n],width[n]
...
524140.030.0
102340.050.0
520242.020.0
167160.060.0
623060.070.0
168298.015.0
>>>
>>>a=vstack([serialnr,width,height])#Alternatively:alldata
inonebigmatrix
>>>printa#Mindtheorderoftherows!
[[1023.5202.6230.1671.1682.5241.]
[50.20.70.60.15.30.]
[40.42.60.60.98.40.]]
>>>indices=lexsort(a)#Sortonlastrow,thenon2ndlastrow,
etc.
>>>a.take(indices,axis=1)
array([[5241.,1023.,5202.,1671.,6230.,1682.],
[30.,50.,20.,60.,70.,15.],
[40.,40.,42.,60.,60.,98.]])
Seealso:sort,argsort
linspace()
>>>fromnumpyimport*
>>>linspace(0,5,num=6)#6evenlyspacednumbersbetween0and5
incl.
array([0.,1.,2.,3.,4.,5.])
>>>linspace(0,5,num=10)#10evenlyspacednumbersbetween0and
5incl.
array([0.,0.55555556,1.11111111,1.66666667,2.22222222,
2.77777778,3.33333333,3.88888889,4.44444444,5.])
>>>linspace(0,5,num=10,endpoint=False)#10evenlyspacednumbers
between0and5EXCL.
array([0.,0.5,1.,1.5,2.,2.5,3.,3.5,4.,4.5])
>>>stepsize=linspace(0,5,num=10,endpoint=False,retstep=True)#
besidestheusualarray,alsoreturnthestepsize
>>>stepsize
(array([0.,0.5,1.,1.5,2.,2.5,3.,3.5,4.,4.5]),0.5)
>>>myarray,stepsize=
linspace(0,5,num=10,endpoint=False,retstep=True)
>>>stepsize
0.5
Seealso:arange,logspace,r_
loadtxt()
>>>fromnumpyimport*
>>>
>>>data=loadtxt("myfile.txt")#myfile.txtcontains4columns
ofnumbers
>>>t,z=data[:,0],data[:,3]#datais2Dnumpyarray
>>>
>>>t,x,y,z=loadtxt("myfile.txt",unpack=True)#tounpackall
columns
>>>t,z=loadtxt("myfile.txt",usecols=(0,3),unpack=True)#to
selectjustafewcolumns
>>>data=loadtxt("myfile.txt",skiprows=7)#toskip7rows
fromtopoffile
>>>data=loadtxt("myfile.txt",comments='!')#use'!'as
commentcharinsteadof'#'
>>>data=loadtxt("myfile.txt",delimiter='')#use''as
columnseparatorinsteadofwhitespace
>>>data=loadtxt("myfile.txt",dtype=int)#filecontains
integersinsteadoffloats
Seealso:savetxt,fromfile
logical_and()
>>>fromnumpyimport*
>>>logical_and(array([0,0,1,1]),array([0,1,0,1]))
array([False,False,False,True],dtype=bool)
>>>logical_and(array([False,False,True,True]),
array([False,True,False,True]))
array([False,False,False,True],dtype=bool)
Seealso:logical_or,logical_not,logical_xor,bitwise_and
logical_not()
>>>fromnumpyimport*
>>>logical_not(array([0,1]))
>>>logical_not(array([False,True]))
Seealso:logical_or,logical_not,logical_xor,bitwise_and
logical_or()
>>>fromnumpyimport*
>>>logical_or(array([0,0,1,1]),array([0,1,0,1]))
>>>logical_or(array([False,False,True,True]),
array([False,True,False,True]))
Seealso:logical_and,logical_not,logical_xor,bitwise_or
logical_xor()
>>>fromnumpyimport*
>>>logical_xor(array([0,0,1,1]),array([0,1,0,1]))
>>>logical_xor(array([False,False,True,True]),
array([False,True,False,True]))
Seealso:logical_or,logical_not,logical_or,bitwise_xor
logspace()
>>>fromnumpyimport*
>>>logspace(2,3,num=6)#6evenlyspacedptsona
logarithmicscale,from10^{2}to10^3incl.
array([1.00000000e02,1.00000000e01,1.00000000e+00,
1.00000000e+01,1.00000000e+02,1.00000000e+03])
>>>logspace(2,3,num=10)#10evenlyspacedptsona
logarithmicscale,from10^{2}to10^3incl.
array([1.00000000e02,3.59381366e02,1.29154967e01,
4.64158883e01,1.66810054e+00,5.99484250e+00,
2.15443469e+01,7.74263683e+01,2.78255940e+02,
1.00000000e+03])
>>>logspace(2,3,num=6,endpoint=False)#6evenlyspacedpts
onalogarithmicscale,from10^{2}to10^3EXCL.
array([1.00000000e02,6.81292069e02,4.64158883e01,
3.16227766e+00,2.15443469e+01,1.46779927e+02])
>>>exp(linspace(log(0.01),log(1000),num=6,endpoint=False))#
forcomparison
array([1.00000000e02,6.81292069e02,4.64158883e01,
3.16227766e+00,2.15443469e+01,1.46779927e+02])
Seealso:arange,linspace,r_
lstsq()
lstsq()ismostoftenusedinthecontextofleastsquaresfittingofdata.Supposeyou
obtainsomenoisydatayasafunctionofavariablet,e.g.velocityasafunctionof
time.Youcanuselstsq()tofitamodeltothedata,ifthemodelislinearinits
parameters,thatisif
y=p0*f0(t)+p1*f1(t)+...+pN1*fN1(t)+noise
wherethepiaretheparametersyouwanttoobtainthroughfittingandthefi(t)are
knownfunctionsoft.Whatfollowsisanexamplehowyoucandothis.
First,fortheexample'ssake,somedataissimulated:
>>>fromnumpyimport*
>>>fromnumpy.randomimportnormal
>>>t=arange(0.0,10.0,0.05)#independentvariable
>>>y=2.0*sin(2.*pi*t*0.6)+2.7*cos(2.*pi*t*0.6)+
normal(0.0,1.0,len(t))
Wewouldliketofitthisdatawith:model(t)=p0*sin(2.*pi*t*0.6)+p1*
cos(2.*pi*t*0.6),wherep0andp1aretheunknownfitparameters.Herewego:
>>>fromnumpy.linalgimportlstsq
>>>Nparam=2#wewanttoestimate2parameters:p_0andp_1
>>>A=zeros((len(t),Nparam),float)#onebigarraywithallthe
f_i(t)
>>>A[:,0]=sin(2.*pi*t*0.6)#f_0(t)stored
>>>A[:,1]=cos(2.*pi*t*0.6)#f_1(t)stored
>>>(p,residuals,rank,s)=lstsq(A,y)
>>>p#ourfinalestimateoftheparametersusingnoisydata
array([1.9315685,2.71165171])
>>>residuals#sumoftheresiduals:sum((p[0]*A[:,0]+p[1]*
A[:,1]y)**2)
array([217.23783374])
>>>rank#rankofthearrayA
2
>>>s#singularvaluesofA
array([10.,10.])
Seealso:pinv,polyfit,solve
mat()
>>>fromnumpyimport*
>>>mat('134569')#matricesarealways2dimensional
matrix([[1,3,4],
[5,6,9]])
>>>a=array([[1,2],[3,4]])
>>>m=mat(a)#convert2darraytomatrix
>>>m
matrix([[1,2],
[3,4]])
>>>a[0]#resultis1dimensional
array([1,2])
>>>m[0]#resultis2dimensional
matrix([[1,2]])
>>>a.ravel()#resultis1dimensional
array([1,2,3,4])
>>>m.ravel()#resultis2dimensional
matrix([[1,2,3,4]])
>>>a*a#elementbyelementmultiplication
array([[1,4],
[9,16]])
>>>m*m#(algebraic)matrixmultiplication
matrix([[7,10],
[15,22]])
>>>a**3#elementwisepower
array([[1,8],
[27,64]])
>>>m**3#matrixmultiplicationm*m*m
matrix([[37,54],
[81,118]])
>>>m.T#transposeofthematrix
matrix([[1,3],
[2,4]])
>>>m.H#conjugatetranspose(differsfrom.Tforcomplex
matrices)
matrix([[1,3],
[2,4]])
>>>m.I#inversematrix
matrix([[2.,1.],
[1.5,0.5]])
Seealso:bmat,array,dot,asmatrix
matrix()
>>>fromnumpyimport*
>>>matrix('134569')#matrixissynonymouswithmat
matrix([[1,3,4],
[5,6,9]])
Seealso:mat,asmatrix
max()
>>>fromnumpyimport*
>>>a=array([10,20,30])
>>>a.max()
30
>>>a=array([[10,50,30],[60,20,40]])
>>>a.max()
60
>>>a.max(axis=0)#foreachofthecolumns,findthemaximum
array([60,50,40])
>>>a.max(axis=1)#foreachoftherows,findthemaximum
array([50,60])
>>>max(a)#alsoexists,butisslower
Seealso:nan,argmax,maximum,ptp
maximum()
>>>fromnumpyimport*
>>>a=array([1,0,5])
>>>b=array([3,2,4])
>>>maximum(a,b)#elementbyelementcomparison
array([3,2,5])
>>>max(a.tolist(),b.tolist())#standardPythonfunctiondoesnot
givethesame!
[3,2,4]
Seealso:minimum,max,argmax
mean()
>>>fromnumpyimport*
>>>a=array([1,2,7])
>>>a.mean()
3.3333333333333335
>>>a=array([[1,2,7],[4,9,6]])
>>>a.mean()
4.833333333333333
>>>a.mean(axis=0)#themeanofeachofthe3columns
array([2.5,5.5,6.5])
>>>a.mean(axis=1)#themeanofeachofthe2rows
array([3.33333333,6.33333333])
Seealso:average,median,var,std,sum
median()
>>>fromnumpyimport*
>>>a=array([1,2,3,4,9])
>>>median(a)
3
>>>a=array([1,2,3,4,9,0])
>>>median(a)
2.5
Seealso:average,mean,var,std
mgrid[]
>>>fromnumpyimport*
>>>m=mgrid[1:3,2:5]#rectangularmeshgridwithxvalues[1,2]
andyvalues[2,3,4]
>>>printm
[[[111]
[222]]
[[234]
[234]]]
>>>m[0,1,2]#xvalueofgridpointwithindexcoordinates(1,2)
2
>>>m[1,1,2]#yvalueofgridpointwithindexcoordinates(1,2)
4
Seealso:indices,ogrid
min()
>>>fromnumpyimport*
>>>a=array([10,20,30])
>>>a.min()
10
>>>a=array([[10,50,30],[60,20,40]])
>>>a.min()
10
>>>a.min(axis=0)#foreachofthecolumns,findtheminimum
array([10,20,30])
>>>a.min(axis=1)#foreachoftherows,findtheminimum
array([10,20])
>>>min(a)#alsoexists,butisslower
Seealso:nan,max,minimum,argmin,ptp
minimum()
>>>fromnumpyimport*
>>>a=array([1,0,5])
>>>b=array([3,2,4])
>>>minimum(a,b)#elementbyelementcomparison
array([1,0,4])
>>>min(a.tolist(),b.tolist())#StandardPythonfunctiondoesnot
givethesame!
[1,0,5]
Seealso:min,maximum,argmin
multiply()
>>>fromnumpyimport*
>>>multiply(array([3,6]),array([4,7]))
array([12,42])
Seealso:dot
nan
>>>fromnumpyimport*
>>>sqrt(array([1.0]))
array([nan])#nan=NaN=NotANumber
>>>x=array([2,nan,1])
>>>isnan(x)#showwhichelementsarenan
array([False,True,False],dtype=bool)
>>>isfinite(x)#showwhichelementsarenotnan/inf/inf
array([True,False,True],dtype=bool)
>>>nansum(x)#sameassum()butignorenanelements
3.0
>>>nanmax(x)#sameasmax()butignorenanelements
2.0
>>>nanmin(x)#sameasmin()butignorenanelements
1.0
>>>nanargmin(x)#sameasargmin()butignorenanelements
2
>>>nanargmax(x)#sameasargmax()butignorenanelements
0
>>>nan_to_num(x)#replaceallnanelementswith0.0
array([2.,0.,1.])
Seealso:inf
ndenumerate()
>>>fromnumpyimport*
>>>a=arange(9).reshape(3,3)+10
>>>a
array([[10,11,12],
[13,14,15],
[16,17,18]])
>>>b=ndenumerate(a)
>>>forposition,valueinb:printposition,value#positionis
theNdimensionalindex
...
(0,0)10
(0,1)11
(0,2)12
(1,0)13
(1,1)14
(1,2)15
(2,0)16
(2,1)17
(2,2)18
Seealso:broadcast,ndindex
ndim
>>>fromnumpyimport*
>>>a=arange(12).reshape(3,4)
>>>a
array([[0,1,2,3],
[4,5,6,7],
[8,9,10,11]])
>>>a.ndim#ahas2axes
2
>>>a.shape=(2,2,3)
array([[[0,1,2],
[3,4,5]],
[[6,7,8],
[9,10,11]]])
>>>a.ndim#nowahas3axes
3
>>>len(a.shape)#sameasndim
3
Seealso:shape
ndindex()
>>>forindexinndindex(4,3,2):
printindex
(0,0,0)
(0,0,1)
(0,1,0)
...
(3,1,1)
(3,2,0)
(3,2,1)
Seealso:broadcast,ndenumerate
newaxis
>>>fromnumpyimport*
>>>x=arange(3)
>>>x
array([0,1,2])
>>>x[:,newaxis]#addanewdimension/axis
array([[0],
[1],
[2]])
>>>x[:,newaxis,newaxis]#addtwonewdimensions/axes
array([[[0]],
[[1]],
[[2]]])
>>>x[:,newaxis]*x
array([[0,0,0],
[0,1,2],
[0,2,4]])
>>>y=arange(3,6)
>>>x[:,newaxis]*y#outerproduct,sameasouter(x,y)
array([[0,0,0],
[3,4,5],
[6,8,10]])
>>>x.shape
(3,)
>>>x[newaxis,:].shape#x[newaxis,:]isequivalenttox[newaxis]
andx[None]
(1,3)
>>>x[:,newaxis].shape
(3,1)
Seealso:[],atleast_1d,atleast_2d,atleast_3d,expand_dims
nonzero()
>>>fromnumpyimport*
>>>x=array([1,0,2,1,0,0,8])
>>>indices=x.nonzero()#findtheindicesofthenonzero
elements
>>>indices
(array([0,2,3,6]),)
>>>x[indices]
array([1,2,1,8])
>>>y=array([[0,1,0],[2,0,3]])
>>>indices=y.nonzero()
>>>indices
(array([0,1,1]),array([1,0,2]))
>>>y[indices[0],indices[1]]#onewayofdoingit,explains
what'sinindices[0]andindices[1]
array([1,2,3])
>>>y[indices]#thiswayisshorter
array([1,2,3])
>>>y=array([1,3,5,7])
>>>indices=(y>=5).nonzero()
>>>y[indices]
array([5,7])
>>>nonzero(y)#functionalsoexists
(array([0,1,2,3]),)
Seealso:[],where,compress,choose,take
ogrid()
>>>fromnumpyimport*
>>>x,y=ogrid[0:3,0:3]#xandyareusefultousewith
broadcastingrules
>>>x
array([[0],
[1],
[2]])
>>>y
array([[0,1,2]])
>>>printx*y#examplehowtousebroadcastingrules
[[000]
[012]
[024]]
Seealso:mgrid
ones()
>>>fromnumpyimport*
>>>ones(5)
array([1.,1.,1.,1.,1.])
>>>ones((2,3),int)
array([[1,1,1],
[1,1,1]])
Seealso:ones_like,zeros,empty,eye,identity
ones_like()
>>>fromnumpyimport*
>>>a=array([[1,2,3],[4,5,6]])
>>>ones_like(a)#onesinitialisedarraywiththesameshapeand
datatypeas'a'
array([[1,1,1],
[1,1,1]])
Seealso:ones,zeros_like
outer()
>>>fromnumpyimport*
>>>x=array([1,2,3])
>>>y=array([10,20,30])
>>>outer(x,y)#outerproduct
array([[10,20,30],
[20,40,60],
[30,60,90]])
Seealso:inner,cross
permutation()
>>>fromnumpyimport*
>>>fromnumpy.randomimportpermutation
>>>permutation(4)#permutationofintegersfrom0to3
array([0,3,1,2])
>>>permutation(4)#anotherpermutationofintegersfrom0to3
array([2,1,0,3])
>>>permutation(4)#yetanotherpermutationofintegersfrom0to
3
array([3,0,2,1])
Seealso:shuffle,bytes,seed
piecewise()
>>>fromnumpyimport*
>>>f1=lambdax:x*x
>>>f2=lambdax:2*x
>>>x=arange(2.,3.,0.1)
>>>condition=(x>1)&(x<2)#booleanarray
>>>y=piecewise(x,condition,[f1,1.])#ifconditionistrue,
returnf1,otherwise1.
>>>y=piecewise(x,fabs(x)<=1,[f1,0])+piecewise(x,x>1,
[f2,0])#0.in]inf,1[,f1in[1,+1],f2in]+1,+inf[
>>>printy
<snip>
Seealso:select
pinv()
>>>fromnumpyimport*
>>>fromnumpy.linalgimportpinv,svd,lstsq
>>>A=array([[1.,3.,5.],[2.,4.,6.]])
>>>b=array([1.,3.])
>>>
>>>#Question:findxsuchthat||A*xb||isminimal
>>>#Answer:x=pinvA*b,withpinvAthepseudoinverseofA
>>>
>>>pinvA=pinv(A)
>>>printpinvA
[[1.333333331.08333333]
[0.333333330.33333333]
[0.666666670.41666667]]
>>>x=dot(pinvA,b)
>>>printx
[1.916666670.666666670.58333333]
>>>
>>>#Relationwithleastsquaresminimisationlstsq()
>>>
>>>x,resids,rank,s=lstsq(A,b)
>>>printx#thesamesolutionforxasabove
[1.916666670.666666670.58333333]
>>>
>>>#Relationwithsingularvaluedecompositionsvd()
>>>
>>>U,sigma,V=svd(A)
>>>S=zeros_like(A.transpose())
>>>forninrange(len(sigma)):S[n,n]=1./sigma[n]
>>>dot(V.transpose(),dot(S,U.transpose()))#=pinv(A)
array([[1.33333333,1.08333333],
[0.33333333,0.33333333],
[0.66666667,0.41666667]])
Seealso:inv,lstsq,solve,svd
poisson()
>>>fromnumpyimport*
>>>fromnumpy.randomimport*
>>>poisson(lam=0.5,size=(2,3))#poissondistributionlambda=0.5
array([[2,0,0],
[1,1,0]])
Seealso:random_sample,uniform,standard_normal,seed
poly1d()
>>>fromnumpyimport*
>>>p1=poly1d([2,3],r=1)#specifypolynomialbyitsroots
>>>printp1
2
1x5x+6
>>>p2=poly1d([2,3],r=0)#specifypolynomialbyits
coefficients
>>>printp2
2x+3
>>>printp1+p2#+,,*,/andeven**aresupported
2
1x3x+9
>>>quotient,remainder=p1/p2#divisiongivesatupplewiththe
quotientandremainder
>>>printquotient,remainder
0.5x3
15
>>>p3=p1*p2
>>>printp3
32
2x7x3x+18
>>>p3([1,2,3,4])#evaluatethepolynomialinthevalues
[1,2,3,4]
array([10,0,0,22])
>>>p3[2]#thecoefficientofx**2
7
>>>p3.r#therootsofthepolynomial
array([1.5,3.,2.])
>>>p3.c#thecoefficientsofthepolynomial
array([2,7,3,18])
>>>p3.o#theorderofthepolynomial
3
>>>printp3.deriv(m=2)#the2ndderivativeofthepolynomial
12x14
>>>printp3.integ(m=2,k=[1,2])#integratepolynomialtwiceand
use[1,2]asintegrationconstants
5432
0.1x0.5833x0.5x+9x+1x+2
polyfit()
>>>fromnumpyimport*
>>>x=array([1,2,3,4,5])
>>>y=array([6,11,18,27,38])
>>>polyfit(x,y,2)#fita2nddegreepolynomialtothedata,
resultisx**2+2x+3
array([1.,2.,3.])
>>>polyfit(x,y,1)#fita1stdegreepolynomial(straightline),
resultis8x4
array([8.,4.])
Seealso:lstsq
prod()
>>>fromnumpyimport*
>>>a=array([1,2,3])
>>>a.prod()#1*2*3=6
6
>>>prod(a)#alsoexists
6
>>>a=array([[1,2,3],[4,5,6]])
>>>a.prod(dtype=float)#specifytypeofoutput
720.0
>>>a.prod(axis=0)#foreachofthe3columns:product
array([4,10,18])
>>>a.prod(axis=1)#foreachofthetworows:product
array([6,120])
Seealso:cumprod,sum
ptp()
>>>fromnumpyimport*
>>>a=array([5,15,25])
>>>a.ptp()#peaktopeak=maximumminimum
20
>>>a=array([[5,15,25],[3,13,33]])
>>>a.ptp()
30
>>>a.ptp(axis=0)#peaktopeakvalueforeachofthe3columns
array([2,2,8])
>>>a.ptp(axis=1)#peaktopeakvalueforeachofthe2rows
array([20,30])
Seealso:max,min
put()
>>>fromnumpimport*
>>>a=array([10,20,30,40])
>>>a.put([60,70,80],[0,3,2])#firstvalues,thenindices
>>>a
array([60,20,80,70])
>>>a[[0,3,2]]=[60,70,80]#sameeffect
>>>a.put([40,50],[0,3,2,1])#ifvaluearrayistooshort,itis
repeated
>>>a
array([40,50,40,50])
>>>put(a,[0,3],[90])#alsoexists,buthereFIRSTindices,
THENvalues
>>>a
array([90,50,40,90])
Seealso:putmask,take
putmask()
>>>fromnumpimport*
>>>a=array([10,20,30,40])
>>>mask=array([True,False,True,True])#sizemask=sizea
>>>a.putmask([60,70,80,90],mask)#firstvalues,thenthemask
>>>a
array([60,20,80,90])
>>>a=array([10,20,30,40])
>>>a[mask]#reference
array([60,80,90])
>>>a[mask]=array([60,70,80,90])#NOTexactlythesameas
putmask
>>>a
array([60,20,70,80])
>>>a.putmask([10,90],mask)#ifvaluearrayistooshort,itis
repeated
>>>a
array([10,20,10,90])
>>>putmask(a,mask,[60,70,80,90])#alsoexists,buthereFIRST
mask,THENvalues
Seealso:put,take
r_[]
>>>fromnumpyimport*
>>>r_[1:5]#sameasarange(1,5)
array([1,2,3,4])
>>>r_[1:10:4]#sameasarange(1,10,4)
array([1,5,9])
>>>r_[1:10:4j]#sameaslinspace(1,10,4),4equallyspaced
elementsbetween1and10inclusive
array([1.,4.,7.,10.])
>>>r_[1:5,7,1:10:4]#sequencesseparatedwithcommasare
concatenated
array([1,2,3,4,7,1,5,9])
>>>r_['r',1:3]#returnamatrix.If1d,resultisa1xNmatrix
matrix([[1,2]])
>>>r_['c',1:3]#returnamatrix.If1d,resultisaNx1matrix
matrix([[1],
[2]])
>>>a=array([[1,2,3],[4,5,6]])
>>>r_[a,a]#concatenationalong1st(default)axis(rowwise,
that'swhyit'scalledr_)
array([[1,2,3],
[4,5,6],
[1,2,3],
[4,5,6]])
>>>r_['1',a,a]#concatenationalonglastaxis,sameasc_[a,a]
array([[1,2,3,1,2,3],
[4,5,6,4,5,6]])
Seealso:c_,s_,arange,linspace,hstack,vstack,column_stack,concatenate,bmat
rand()
>>>fromnumpyimport*
>>>fromnumpy.randomimport*
>>>rand(3,2)
array([[0.65159297,0.78872335],
[0.09385959,0.02834748],
[0.8357651,0.43276707]])
Seealso:random_sample,seed
randint()
Synonymforrandom_integers()
Seerandom_integers
randn()
>>>randn(2,3)
array([[1.22497074,0.29508896,0.75040033],
[0.54822685,0.98032155,1.40467696]])
Seealso:standard_normal,poisson,seed
random_integers()
>>>fromnumpyimport*
>>>fromnumpy.randomimport*
>>>random_integers(1,5,(2,2))
array([[3,1],
[1,0]])
Seealso:random_sample,uniform,poisson,seed
random_sample()
>>>fromnumpyimport*
>>>fromnumpy.randomimport*
>>>random_sample((3,2))
array([[0.76228008,0.00210605],
[0.44538719,0.72154003],
[0.22876222,0.9452707]])
Seealso:ranf,sample,rand,seed
ranf()
Synonymforrandom_sample
Seerandom_sample,sample
ravel()
>>>fromnumpyimport*
>>>a=array([[1,2],[3,4]])
>>>a.ravel()#1dversionofa
array([1,2,3,4])
>>>b=a[:,0].ravel()#a[:,0]doesnotoccupyasinglememory
segment,thusbisacopy,notareference
>>>b
array([1,3])
>>>c=a[0,:].ravel()#a[0,:]occupiesasinglememorysegment,
thuscisareference,notacopy
>>>c
array([1,2])
>>>b[0]=1
>>>c[1]=2
>>>a
array([[1,2],
[3,4]])
>>>ravel(a)#alsoexists
Seealso:flatten
real
>>>fromnumpyimport*
>>>a=array([1+2j,3+4j,5+6j])
>>>a.real
array([1.,3.,5.])
>>>a.real=9
>>>a
array([9.+2.j,9.+4.j,9.+6.j])
>>>a.real=array([9,8,7])
>>>a
array([9.+2.j,8.+4.j,7.+6.j])
Seealso:imag,angle
recarray()
>>>fromnumpyimport*
>>>num=2
>>>a=recarray(num,formats='i4,f8,f8',names='id,x,y')
>>>a['id']=[3,4]
>>>a['id']
array([3,4])
>>>a=rec.fromrecords([(35,1.2,7.3),(85,9.3,3.2)],
names='id,x,y')#fromrecordsisinthenumpy.recsubmodule
>>>a['id']
array([35,85])
Seealso:array,dtype
reduce()
>>>fromnumpyimport*
>>>add.reduce(array([1.,2.,3.,4.]))#computes
((((1.)+2.)+3.)+4.)
10.0
>>>multiply.reduce(array([1.,2.,3.,4.]))#worksalsowithother
operands.Computes((((1.)*2.)*3.)*4.)
24.0
>>>add.reduce(array([[1,2,3],[4,5,6]]),axis=0)#reduceevery
columnseparately
array([5,7,9])
>>>add.reduce(array([[1,2,3],[4,5,6]]),axis=1)#reduceevery
rowseparately
array([6,15])
Seealso:accumulate,sum,prod
repeat()
>>>fromnumpyimport*
>>>repeat(7.,4)
array([7.,7.,7.,7.])
>>>a=array([10,20])
>>>a.repeat([3,2])
array([10,10,10,20,20])
>>>repeat(a,[3,2])#alsoexists
>>>a=array([[10,20],[30,40]])
>>>a.repeat([3,2,1,1])
array([10,10,10,20,20,30,40])
>>>a.repeat([3,2],axis=0)
array([[10,20],
[10,20],
[10,20],
[30,40],
[30,40]])
>>>a.repeat([3,2],axis=1)
array([[10,10,10,20,20],
[30,30,30,40,40]])
Seealso:tile
reshape()
>>>fromnumpyimport*
>>>x=arange(12)
>>>x.reshape(3,4)#arraywith3rowsand4columns.3x4=12.
Totalnumberofelementsisalwaysthesame.
array([[0,1,2,3],
[4,5,6,7],
[8,9,10,11]])
>>>x.reshape(3,2,2)#3x2x2array3x2x2=12.xitselfdoes
_not_change.
array([[[0,1],
[2,3]],
[[4,5],
[6,7]],
[[8,9],
[10,11]]])
>>>x.reshape(2,1)#'missing'1valueniscalculatedsothat
2xn=12,son=6
array([[0,1,2,3,4,5],
[6,7,8,9,10,11]])
>>>x.reshape(12)#reshape(1,12)isnotthesameasreshape(12)
array([0,1,2,3,4,5,6,7,8,9,10,11])
>>>reshape(x,(2,6))#Separatefunctionreshape()alsoexists
Seealso:shape,resize
resize()
>>>fromnumpyimport*
>>>a=array([1,2,3,4])
>>>a.resize(2,2)#changesshapeof'a'itself
>>>printa
[[12]
[34]]
>>>a.resize(3,2)#reallocatesmemoyof'a'tochangenrof
elements,fillsexcesselementswith0
>>>printa
[[12]
[34]
[00]]
>>>a.resize(2,4)
>>>printa
[[1234]
[0000]]
>>>a.resize(2,1)#throwsawayelementsof'a'tofitnewshape
>>>printa
[[1]
[2]]
But,thereisacaveat:
>>>b=array([1,2,3,4])
>>>c=b#cisreferencetob,itdoesn't'own'itsdata
>>>c.resize(2,2)#noproblem,nrofelementsdoesn'tchange
>>>c.resize(2,3)#doesn'twork,cisonlyareference
Traceback(mostrecentcalllast):
File"<stdin>",line1,in?
ValueError:cannotresizeanarraythathasbeenreferencedoris
referencing
anotherarrayinthisway.Usetheresizefunction
>>>b.resize(2,3)#doesn'twork,bisreferencedbyanotherarray
Traceback(mostrecentcalllast):
File"<stdin>",line1,in?
ValueError:cannotresizeanarraythathasbeenreferencedoris
referencing
anotherarrayinthisway.Usetheresizefunction
andit'snotalwaysobviouswhatthereferenceis:
>>>d=arange(4)
>>>d
array([0,1,2,3])
>>>d.resize(5)#doesn'twork,butwhere'sthereference?
Traceback(mostrecentcalllast):
File"<stdin>",line1,in?
ValueError:cannotresizeanarraythathasbeenreferencedoris
referencing
anotherarrayinthisway.Usetheresizefunction
>>>_#'_'wasareferencetod!
array([0,1,2,3])
>>>d=resize(d,5)#thisdoeswork,however
>>>d
array([0,1,2,3,0])
Seealso:reshape
rollaxis()
>>>fromnumpyimport*
>>>a=arange(3*4*5).reshape(3,4,5)
>>>a.shape
(3,4,5)
>>>b=rollaxis(a,1,0)#transposearraysothataxis1is
'rolled'beforeaxis0
>>>b.shape
(4,3,5)
>>>b=rollaxis(a,0,2)#transposearraysothataxis0is
'rolled'beforeaxis2
>>>b.shape
(4,3,5)
Seealso:swapaxes,transpose
round()
round(decimals=0,out=None)>referencetoroundedvalues.
>>>fromnumpyimport*
>>>array([1.2345,1.647]).round()#roundstheitems.Type
remainsfloat64.
array([1.,2.])
>>>array([1,1]).round()#integerarraysstayastheyare
array([1,1])
>>>array([1.2345,1.647]).round(decimals=1)#roundto1decimal
place
array([1.2,1.6])
>>>array([1.2345+2.34j,1.6470.238j]).round()#bothrealand
complexpartsarerounded
array([1.+2.j,2.0.j])
>>>array([0.0,0.5,1.0,1.5,2.0,2.5]).round()#numpyrounds
x.5tonearesteven.
array([0.,0.,1.,2.,2.,2.])
>>>a=zeros(3,dtype=int)
>>>array([1.2345,1.647,3.141]).round(out=a)#differentoutput
arraysmaybespecified
array([1,2,3])
>>>a#andtheoutputiscasttothenewtype
array([1,2,3])
>>>round_(array([1.2345,1.647]))#round_isthefunctional
form.>acopy.
array([1.,2.])
>>>around(array([1.2345,1.647]))#aroundisanaliasof
round_.
array([1.,2.])
Seealso:ceil,floor,fix,astype
rot90()
>>>fromnumpyimport*
>>>a=arange(12).reshape(4,3)
>>>a
array([[0,1,2],
[3,4,5],
[6,7,8],
[9,10,11]])
>>>rot90(a)#'rotate'thematrix90degrees
array([[2,5,8,11],
[1,4,7,10],
[0,3,6,9]])
Seealso:fliplr,flipud
s_[]
>>>fromnumpyimport*
>>>s_[1:5]#easyslicegenerating.Seer_[]examples.
slice(1,5,None)
>>>s_[1:10:4]
slice(1,10,4)
>>>s_[1:10:4j]
slice(1,10,4j)
>>>s_['r',1:3]#toreturnamatrix.If1d,resultisa1xN
matrix
('r',slice(1,3,None))
>>>s_['c',1:3]#toreturnamatrix.If1d,resultisaNx1
matrix
('c',slice(1,3,None))
Seealso:r_,c_,slice,index_exp
sample()
Synonymforrandom_sample
Seealso:random_sample,ranf
savetxt()
>>>fromnumpyimport*
>>>savetxt("myfile.txt",data)#datais2Darray
>>>savetxt("myfile.txt",x)#xis1Darray.1columninfile.
>>>savetxt("myfile.txt",(x,y))#x,yare1Darrays.2rowsin
file.
>>>savetxt("myfile.txt",transpose((x,y)))#x,yare1Darrays.2
columnsinfile.
>>>savetxt("myfile.txt",transpose((x,y)),fmt='%6.3f')#usenew
formatinsteadof'%.18e'
>>>savetxt("myfile.txt",data,delimiter='')#use''to
separatecolumnsinsteadofspace
Seealso:loadtxt,tofile
searchsorted()
searchsorted(keys,side="left")
>>>fromnumpyimport*
>>>a=array([1,2,2,3])#ais1Dandinascendingorder.
>>>a.searchsorted(2)#sidedefaultsto"left"
1#a[1]isthefirstelementina>=2
>>>a.searchsorted(2,side='right')#lookfortheotherendof
therunoftwos
3#a[3]isthefirstelementina>2
>>>a.searchsorted(4)#4isgreaterthananyelementina
4#thereturnedindexis1pasttheendofa.
>>>a.searchsorted([[1,2],[2,3]])#whoa,fancykeys
array([[0,1],#thereturnedarrayhasthesameshapeasthekeys
[1,3]])
>>>searchsorted(a,2)#thereisafunctionalform
1
Seealso:sort,histogram
seed()
>>>seed([1])#seedthepseudorandomnumbergenerator
>>>rand(3)
array([0.13436424,0.84743374,0.76377462])
>>>seed([1])
>>>rand(3)
array([0.13436424,0.84743374,0.76377462])
>>>rand(3)
array([0.25506903,0.49543509,0.44949106])
select()
>>>fromnumpyimport*
>>>x=array([5.,2.,1.,0.,4.,1.,3.,10.])
>>>select([x<0,x==0,x<=5],[x0.1,0.0,x+0.2],default=
100.)
array([5.2,2.1,1.2,0.,4.2,1.1,3.2,100.])
>>>
>>>#Thisishowitworks:
>>>
>>>result=zeros_like(x)
>>>forninrange(len(x)):
...ifx[n]<0:result[n]=x[n]0.1#Theorderofthe
conditionsmatters.Thefirstonethat
...elifx[n]==0:result[n]=0.0#matches,willbe'selected'.
...elifx[n]<=5:result[n]=x[n]+0.2
...else:result[n]=100.#Thedefaultisusedwhennoneofthe
conditionsmatch
...
>>>result
array([5.2,2.1,1.2,0.,4.2,1.1,3.2,100.])
Seealso:choose,piecewise
set_printoptions()
>>>fromnumpyimport*
>>>x=array([pi,1.e200])
>>>x
array([3.14159265e+000,1.00000000e200])
>>>set_printoptions(precision=3,suppress=True)#3digitsbehind
decimalpoint+suppresssmallvalues
>>>x
array([3.142,0.])
>>>
>>>help(set_printoptions)#seehelp()forkeywords
'threshold','edgeitems'and'linewidth'
shape
>>>fromnumpyimport*
>>>x=arange(12)
>>>x.shape
(12,)
>>>x.shape=(3,4)#arraywith3rowsand4columns.3x4=12.
Totalnumberofelementsisalwaysthesame.
>>>x
array([[0,1,2,3],
[4,5,6,7],
[8,9,10,11]])
>>>x.shape=(3,2,2)#3x2x2array3x2x2=12.xitself_does_
change,unlikereshape().
>>>x
array([[[0,1],
[2,3]],
[[4,5],
[6,7]],
[[8,9],
[10,11]]])
>>>x.shape=(2,1)#'missing'1valueniscalculatedsothat
2xn=12,son=6
>>>x
array([[0,1,2,3,4,5],
[6,7,8,9,10,11]])
>>>x.shape=12#x.shape=(1,12)isnotthesameasx.shape=
12
>>>x
array([0,1,2,3,4,5,6,7,8,9,10,11])
Seealso:reshape
shuffle()
>>>fromnumpyimport*
>>>fromnumpy.randomimportshuffle
>>>x=array([1,50,1,3])
>>>shuffle(x)#shuffletheelementsofx
>>>printx
[13501]
>>>x=['a','b','c','z']
>>>shuffle(x)#workswithanysequence
>>>printx
['a','c','z','b']
Seealso:permutation,bytes
slice()
>>>s=slice(3,9,2)#sliceobjectsexistoutsidenumpy
>>>fromnumpyimport*
>>>a=arange(20)
>>>a[s]
array([3,5,7])
>>>a[3:9:2]#samething
array([3,5,7])
Seealso:[],...,newaxis,s_,ix_,indices,index_exp
solve()
>>>fromnumpyimport*
>>>fromnumpy.linalgimportsolve
>>>
>>>#Thesystemofequationswewanttosolvefor(x0,x1,x2):
>>>#3*x0+1*x1+5*x2=6
>>>#1*x0+8*x2=7
>>>#2*x0+1*x1+4*x2=8
>>>
>>>a=array([[3,1,5],[1,0,8],[2,1,4]])
>>>b=array([6,7,8])
>>>x=solve(a,b)
>>>printx#Thisisoursolution
[3.285714299.428571431.28571429]
>>>
>>>dot(a,x)#Justcheckingifweindeedobtaintherighthand
side
array([6.,7.,8.])
Seealso:inv
sometrue()
>>>fromnumpyimport*
>>>b=array([True,False,True,True])
>>>sometrue(b)
True
>>>a=array([1,5,2,7])
>>>sometrue(a>=5)
True
Seealso:alltrue,all,any
sort()
sort(axis=1,kind="quicksort")
>>>fromnumpyimport*
>>>a=array([2,0,8,4,1])
>>>a.sort()#inplacesortingwithquicksort(default)
>>>a
array([0,1,2,4,8])
>>>a.sort(kind='mergesort')#algorithmoptionsare'quicksort',
'mergesort'and'heapsort'
>>>a=array([[8,4,1],[2,0,9]])
>>>a.sort(axis=0)
>>>a
array([[2,0,1],
[8,4,9]])
>>>a=array([[8,4,1],[2,0,9]])
>>>a.sort(axis=1)#defaultaxis=1
>>>a
array([[1,4,8],
[0,2,9]])
>>>sort(a)#thereisafunctionalform
Seealso:argsort,lexsort
split()
>>>fromnumpyimport*
>>>a=array([[1,2,3,4],[5,6,7,8]])
>>>split(a,2,axis=0)#splitain2parts.rowwise
array([[1,2,3,4]]),array([[5,6,7,8]])]
>>>split(a,4,axis=1)#splitain4parts,columnwise
[array([[1],
[5]]),array([[2],
[6]]),array([[3],
[7]]),array([[4],
[8]])]
>>>split(a,3,axis=1)#impossibletosplitin3equalparts>
error(SEE:array_split)
Traceback(mostrecentcalllast):
<snip>
ValueError:arraysplitdoesnotresultinanequaldivision
>>>split(a,[2,3],axis=1)#makeasplitbeforethe2ndandthe
3rdcolumn
[array([[1,2],
[5,6]]),array([[3],
[7]]),array([[4],
[8]])]
ERROR:EOFinmultilinestatement
Seealso:dsplit,hsplit,vsplit,array_split,concatenate
squeeze()
>>>fromnumpyimport*
>>>a=arange(6)
>>>a=a.reshape(1,2,1,1,3,1)
>>>a
array([[[[[[0],
[1],
[2]]]],
[[[[3],
[4],
[5]]]]]])
>>>a.squeeze()#resulthasshape2x3,alldimensionswithlength
1areremoved
array([[0,1,2],
[3,4,5]])
>>>squeeze(a)#alsoexists
std()
>>>fromnumpyimport*
>>>a=array([1.,2,7])
>>>a.std()#normalizedbyN(notN1)
2.6246692913372702
>>>a=array([[1.,2,7],[4,9,6]])
>>>a.std()
2.793842435706702
>>>a.std(axis=0)#standarddeviationofeachofthe3columns
array([1.5,3.5,0.5])
>>>a.std(axis=1)#standarddeviationofeachofthe2columns
array([2.62466929,2.05480467])
Seealso:mean,var,cov
standard_normal()
>>>standard_normal((2,3))
array([[1.12557608,0.13464922,0.35682992],
[1.54090277,1.21551589,1.82854551]])
Seealso:randn,uniform,poisson,seed
sum()
>>>fromnumpyimport*
>>>a=array([1,2,3])
>>>a.sum()
6
>>>sum(a)#alsoexists
>>>a=array([[1,2,3],[4,5,6]])
>>>a.sum()
21
>>>a.sum(dtype=float)#specifytypeofoutput
21.0
>>>a.sum(axis=0)#sumoverrowsforeachofthe3columns
array([5,7,9])
>>>a.sum(axis=1)#sumovercolumnsforeachofthe2rows
array([6,15])
Seealso:accumulate,nan,cumsum,prod
svd()
>>>fromnumpyimport*
>>>fromnumpy.linalgimportsvd
>>>A=array([[1.,3.,5.],[2.,4.,6.]])#Aisa(2x3)matrix
>>>U,sigma,V=svd(A)
>>>printU#Uisa(2x2)unitarymatrix
[[0.619629480.78489445]
[0.784894450.61962948]]
>>>printsigma#nonzerodiagonalelementsofSigma
[9.525518090.51430058]
>>>printV#Visa(3x3)unitarymatrix
[[0.22984770.524744820.81964194]
[0.883461020.240782490.40189603]
[0.408248290.816496580.40824829]]
>>>Sigma=zeros_like(A)#constructingSigmafromsigma
>>>n=min(A.shape)
>>>Sigma[:n,:n]=diag(sigma)
>>>printdot(U,dot(Sigma,V))#A=U*Sigma*V
[[1.3.5.]
[2.4.6.]]
Seealso:pinv
swapaxes()
>>>fromnumpyimport*
>>>a=arange(30)
>>>a=a.reshape(2,3,5)
>>>a
array([[[0,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]]])
>>>b=a.swapaxes(1,2)#swapthe2ndandthe3rdaxis
>>>b
array([[[0,5,10],
[1,6,11],
[2,7,12],
[3,8,13],
[4,9,14]],
[[15,20,25],
[16,21,26],
[17,22,27],
[18,23,28],
[19,24,29]]])
>>>b.shape
(2,5,3)
>>>b[0,0,0]=1#beawarethatbisareference,notacopy
>>>printa[0,0,0]
Seealso:transpose,rollaxis
T
>>>fromnumpyimport*
>>>x=array([[1.,2.],[3.,4.]])
>>>x
array([[1.,2.],
[3.,4.]])
>>>x.T#shortcutfortranspose()
array([[1.,3.],
[2.,4.]])
Seealso:transpose
take()
>>>fromnumpyimport*
>>>a=array([10,20,30,40])
>>>a.take([0,0,3])#[0,0,3]isasetofindices
array([10,10,40])
>>>a[[0,0,3]]#thesameeffect
array([10,10,40])
>>>a.take([[0,1],[0,1]])#shapeofreturnarraydependsonshape
ofindicesarray
array([[10,20],
[10,20]])
>>>a=array([[10,20,30],[40,50,60]])
>>>a.take([0,2],axis=1)
array([[10,30],
[40,60]])
>>>take(a,[0,2],axis=1)#alsoexists
Seealso:[],put,putmask,compress,choose
tensordot()
>>>fromnumpyimport*
>>>a=arange(60.).reshape(3,4,5)
>>>b=arange(24.).reshape(4,3,2)
>>>c=tensordot(a,b,axes=([1,0],[0,1]))#sumoverthe1stand
2nddimensions
>>>c.shape
(5,2)
>>>#Aslowerbutequivalentwayofcomputingthesame:
>>>c=zeros((5,2))
>>>foriinrange(5):
...forjinrange(2):
...forkinrange(3):
...forninrange(4):
...c[i,j]+=a[k,n,i]*b[n,k,j]
...
Seealso:dot
tile()
>>>fromnumpyimport*
>>>a=array([10,20])
>>>tile(a,(3,2))#concatenate3x2copiesofatogether
array([[10,20,10,20],
[10,20,10,20],
[10,20,10,20]])
>>>tile(42.0,(3,2))#worksforscalars,too
array([[42.,42.],
[42.,42.],
[42.,42.]])
>>>tile([[1,2],[4,8]],(2,3))#worksfor2darraysandlist
literals,too
array([[1,2,1,2,1,2],
[4,8,4,8,4,8],
[1,2,1,2,1,2],
[4,8,4,8,4,8]])
Seealso:hstack,vstack,r_,c_,concatenate,repeat
tofile()
>>>fromnumpyimport*
>>>x=arange(10.)
>>>y=x**2
>>>y.tofile("myfile.dat")#binaryformat
>>>y.tofile("myfile.txt",sep='',format="%e")#asciiformat,
onerow,expnotation,valuesseparatedby1space
>>>y.tofile("myfile.txt",sep='\n',format="%e")#ascii
format,onecolumn,exponentialnotation
Seealso:fromfile,loadtxt,savetxt
tolist()
>>>fromnumpyimport*
>>>a=array([[1,2],[3,4]])
>>>a.tolist()#converttoastandardpythonlist
[[1,2],[3,4]]
trace()
>>>fromnumpyimport*
>>>a=arange(12).reshape(3,4)
>>>a
array([[0,1,2,3],
[4,5,6,7],
[8,9,10,11]])
>>>a.diagonal()
array([0,5,10])
>>>a.trace()
15
>>>a.diagonal(offset=1)
array([1,6,11])
>>>a.trace(offset=1)
18
Seealso:diag,diagonal
transpose()
Averysimpleexample:
>>>a=array([[1,2,3],[4,5,6]])
>>>printa.shape
(2,3)
>>>b=a.transpose()
>>>printb
[[14]
[25]
[36]]
>>>printb.shape
(3,2)
Fromthis,amoreelaborateexamplecanbeunderstood:
>>>a=arange(30)
>>>a=a.reshape(2,3,5)
>>>a
array([[[0,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]]])
>>>b=a.transpose()
>>>b
array([[[0,15],
[5,20],
[10,25]],
[[1,16],
[6,21],
[11,26]],
[[2,17],
[7,22],
[12,27]],
[[3,18],
[8,23],
[13,28]],
[[4,19],
[9,24],
[14,29]]])
>>>b.shape
(5,3,2)
>>>b=a.transpose(1,0,2)#Firstaxis1,thenaxis0,thenaxis
2
>>>b
array([[[0,1,2,3,4],
[15,16,17,18,19]],
[[5,6,7,8,9],
[20,21,22,23,24]],
[[10,11,12,13,14],
[25,26,27,28,29]]])
>>>b.shape
(3,2,5)
>>>b=transpose(a,(1,0,2))#Aseparatetranspose()function
alsoexists
Seealso:T,swapaxes,rollaxis
tri()
>>>fromnumpyimport*
>>>tri(3,4,k=0,dtype=float)#3x4matrixofFloats,triangular,
thek=0thdiagonalandbelowis1,theupperpartis0
array([[1.,0.,0.,0.],
[1.,1.,0.,0.],
[1.,1.,1.,0.]])
>>>tri(3,4,k=1,dtype=int)
array([[1,1,0,0],
[1,1,1,0],
[1,1,1,1]])
Seealso:tril,triu
tril()
>>>fromnumpyimport*
>>>a=arange(10,100,10).reshape(3,3)
>>>a
array([[10,20,30],
[40,50,60],
[70,80,90]])
>>>tril(a,k=0)
array([[10,0,0],
[40,50,0],
[70,80,90]])
>>>tril(a,k=1)
array([[10,20,0],
[40,50,60],
[70,80,90]])
Seealso:tri,triu
trim_zeros()
>>>fromnumpyimport*
>>>x=array([0,0,0,1,2,3,0,0])
>>>trim_zeros(x,'f')#removezerosatthefront
array([1,2,3,0,0])
>>>trim_zeros(x,'b')#removezerosattheback
array([0,0,0,1,2,3])
>>>trim_zeros(x,'bf')#removezerosatthebackandthefront
array([1,2,3])
Seealso:compress
triu()
>>>fromnumpyimport*
>>>a=arange(10,100,10).reshape(3,3)
>>>a
array([[10,20,30],
[40,50,60],
[70,80,90]])
>>>triu(a,k=0)
array([[10,20,30],
[0,50,60],
[0,0,90]])
>>>triu(a,k=1)
array([[0,20,30],
[0,0,60],
[0,0,0]])
Seealso:tri,tril
typeDict()
>>>fromnumpyimport*
>>>typeDict['short']
<type'numpy.int16'>
>>>typeDict['uint16']
<type'numpy.uint16'>
>>>typeDict['void']
<type'numpy.void'>
>>>typeDict['S']
<type'numpy.string_'>
Seealso:dtype,cast
uniform()
>>>fromnumpyimport*
>>>fromnumpy.randomimport*
>>>uniform(low=0,high=10,size=(2,3))#uniformnumbersinrange
[0,10)
array([[6.66689951,4.50623001,4.69973967],
[6.52977732,3.24688284,5.01917021]])
Seealso:standard_normal,poisson,seed
unique()
>>>fromnumpyimport*
>>>x=array([2,3,2,1,0,3,4,0])
>>>unique(x)#removedoublevalues
array([0,1,2,3,4])
Seealso:compress,unique1d
unique1d()
>>>np.unique1d([1,1,2,2,3,3])
array([1,2,3])
>>>a=np.array([[1,1],[2,3]])
>>>np.unique1d(a)
array([1,2,3])
>>>np.unique1d([1,2,6,4,2,3,2],return_index=True)
(array([1,2,3,4,6]),array([0,1,5,3,2]))
>>>x=[1,2,6,4,2,3,2]
>>>u,i=np.unique1d(x,return_inverse=True)
>>>u
array([1,2,3,4,6])
>>>i
array([0,1,4,3,1,2,1])
>>>[u[p]forpini]
[1,2,6,4,2,3,2]
Seealso:compress,unique
vander()
>>>fromnumpyimport*
>>>x=array([1,2,3,5])
>>>N=3
>>>vander(x,N)#Vandermondematrixofthevectorx
array([[1,1,1],
[4,2,1],
[9,3,1],
[25,5,1]])
>>>column_stack([x**(N1i)foriinrange(N)])#tounderstand
whataVandermondematrixcontains
array([[1,1,1],
[4,2,1],
[9,3,1],
[25,5,1]])
var()
>>>fromnumpyimport*
>>>a=array([1,2,7])
>>>a.var()#normalisedwithN(notN1)
6.8888888888888875
>>>a=array([[1,2,7],[4,9,6]])
>>>a.var()
7.8055555555555571
>>>a.var(axis=0)#thevarianceofeachofthe3columns
array([2.25,12.25,0.25])
>>>a.var(axis=1)#thevarianceofeachofthe2rows
array([6.88888889,4.22222222])
Seealso:cov,std,mean
vdot()
>>>fromnumpyimport*
>>>x=array([1+2j,3+4j])
>>>y=array([5+6j,7+8j])
>>>vdot(x,y)#conj(x)*y=(12j)*(5+6j)+(34j)*(7+8j)
(708j)
Seealso:dot,inner,cross,outer
vectorize()
>>>fromnumpyimport*
>>>defmyfunc(x):
...ifx>=0:returnx**2
...else:returnx
...
>>>myfunc(2.)#worksfine
4.0
>>>myfunc(array([2,2]))#doesn'twork,tryit...
<snip>
>>>vecfunc=vectorize(myfunc,otypes=[float])#declarethe
returntypeasfloat
>>>vecfunc(array([2,2]))#worksfine!
array([2.,4.])
Seealso:apply_along_axis,apply_over_axes
view()
>>>fromnumpyimport*
>>>a=array([1.,2.])
>>>a.view()#newarrayreferringtothesamedataas'a'
array([1.,2.])
>>>a.view(complex)#pretendthataismadeupofcomplexnumbers
array([1.+2.j])
>>>a.view(int)#view(type)isNOTthesameasastype(type)!
array([0,1072693248,0,1073741824])
>>>
>>>mydescr=dtype({'names':['gender','age'],'formats':['S1',
'i2']})
>>>a=array([('M',25),('F',30)],dtype=mydescr)#arraywith
records
>>>b=a.view(recarray)#converttoarecordarray,namesare
nowattributes
>>>>>>a['age']#workswith'a'butnotwith'b'
array([25,30],dtype=int16)
>>>b.age#workswith'b'butnotwith'a'
array([25,30],dtype=int16)
Seealso:copy
vonmises()
>>>fromnumpyimport*
>>>fromnumpy.randomimport*
>>>vonmises(mu=1,kappa=1,size=(2,3))#VonMisesdistribution
mean=1.0,kappa=1
array([[0.81960554,1.37470839,0.15700173],
[1.2974554,2.94229797,0.32462307]])
>>>frompylabimport*#histogramplotexample
>>>hist(vonmises(1,1,(10000)),50)
Seealso:random_sample,uniform,standard_normal,seed
vsplit()
>>>fromnumpyimport*
>>>a=array([[1,2],[3,4],[5,6],[7,8]])
>>>vsplit(a,2)#split,rowwise,in2equalparts
[array([[1,2],
[3,4]]),array([[5,6],
[7,8]])]
>>>vsplit(a,[1,2])#split,rowwise,beforerow1andbeforerow
2
[array([[1,2]]),array([[3,4]]),array([[5,6],
[7,8]])]
Seealso:split,array_split,dsplit,hsplit,vstack
vstack()
>>>fromnumpyimport*
>>>a=array([1,2])
>>>b=array([[3,4],[5,6]])
>>>vstack((a,b,a))#onlythefirstdimensionofthearraysis
allowedtobedifferent
array([[1,2],
[3,4],
[5,6],
[1,2]])
Seealso:hstack,column_stack,concatenate,dstack,vsplit
weibull()
>>>fromnumpyimport*
>>>fromnumpy.randomimport*
>>>weibull(a=1,size=(2,3))#Ithinkaistheshapeparameter
array([[0.08303065,3.41486412,0.67430149],
[0.41383893,0.93577601,0.45431195]])
>>>frompylabimport*#histogramplotexample
>>>hist(weibull(5,(1000)),50)
Seealso:random_sample,uniform,standard_normal,seed
where()
>>>fromnumpyimport*
>>>a=array([3,5,7,9])
>>>b=array([10,20,30,40])
>>>c=array([2,4,6,8])
>>>where(a<=6,b,c)
array([10,20,6,8])
>>>where(a<=6,b,1)
array([10,20,1,1])
>>>indices=where(a<=6)#returnsatuplethearraycontains
indices.
>>>indices
(array([0,1]),)
>>>b[indices]
array([10,20])
>>>b[a<=6]#analternativesyntax
array([10,20])
>>>d=array([[3,5,7,9],[2,4,6,8]])
>>>where(d<=6)#tuplewithfirstalltherowindices,thenall
thecolumnindices
(array([0,0,1,1,1]),array([0,1,0,1,2]))
Beawareofthedifferencebetweenx[listofbools]andx[listofintegers]!
>>>fromnumpyimport*
>>>x=arange(5,0,1)
>>>printx
[54321]
>>>criterion=(x<=2)|(x>=5)
>>>criterion
array([True,False,False,True,True],dtype=bool)
>>>indices=where(criterion,1,0)
>>>printindices
[10011]
>>>x[indices]#integers!
array([4,5,5,4,4])
>>>x[criterion]#bools!
array([5,2,1])
>>>indices=where(criterion)
>>>printindices
(array([0,3,4]),)
>>>x[indices]
array([5,2,1])
Seealso:[],nonzero,clip
zeros()
>>>fromnumpyimport*
>>>zeros(5)
array([0.,0.,0.,0.,0.])
>>>zeros((2,3),int)
array([[0,0,0],
[0,0,0]])
Seealso:zeros_like,ones,empty,eye,identity
zeros_like()
>>>fromnumpyimport*
>>>a=array([[1,2,3],[4,5,6]])
>>>zeros_like(a)#withzerosinitialisedarraywiththesame
shapeanddatatypeas'a'
array([[0,0,0],
[0,0,0]])
Seealso:ones_like,zeros
CategoryCategory
NumpyExampleList(ltimaedicin2011120820:40:16efectuadapor
SimonBull)