Professional Documents
Culture Documents
1) Lectura NumPy 12-21 PDF
1) Lectura NumPy 12-21 PDF
14
Indexing with None
None is a special index that inserts a new axis in the array at the specified
location. Each None increases the arrays dimensionality by 1.
a 0 1 2
0
2
1 1
0 1 2 0
2
15
Setting Array Elements
ARRAY INDEXING BEWARE OF TYPE
>>> a[0] COERSION
0 >>> a.dtype
>>> a[0] = 10 dtype('int32')
>>> a
[10, 1, 2, 3] # assigning a float to into # an
int32 array will
FILL
# truncate decimal part.
# set all values in an array. >>> a[0] = 10.6
>>> a.fill(0) >>> a
>>> a [10, 1, 2, 3]
[0, 0, 0, 0]
# fill has the same behavior
# This also works, but may >>> a.fill(-4.8)
# be slower. >>> a
>>> a[:] = 1 [-4, -4, -4, -4]
>>> a
[1, 1, 1, 1] 16
Multi-Dimensional Arrays
MULTI-DIMENSIONAL ARRAYS NUMBER OF DIMENSIONS
>>> a = array([[ 0, 1, 2, 3], >>> a.ndims
[10,11,12,13]]) 2
>>> a
array([[ 0, 1, 2, 3], GET/SET ELEMENTS
[10,11,12,13]]) >>> a[1,3]
(ROWS,COLUMNS) 13 column
row
>>> a.shape >>> a[1,3] = -1
(2, 4) >>> a
>>> shape(a) array([[ 0, 1, 2, 3],
(2, 4) [10,11,12,-1]])
ELEMENT COUNT ADDRESS FIRST ROW USING
>>> a.size SINGLE INDEX
8 >>> a[1]
>>> size(a) array([10, 11, 12, -1])
8
17
Array Slicing
>>> a[4:,4:] 10 11 12 13 14 15
array([[44, 45], 20 21 22 23 24 25
[54, 55]])
30 31 32 33 34 35
>>> a[:,2]
40 41 42 43 44 45
array([2,12,22,32,42,52])
STRIDES ARE ALSO POSSIBLE 50 51 52 53 54 55
>>> a[2::2,::2]
array([[20, 22, 24],
[40, 42, 44]])
18
Slices Are References
>>> a = array((0,1,2,3,4))
# changing b changed a!
>>> a
array([ 1, 2, 10, 3, 4])
19
Fancy Indexing
a 0 10 20 30 40 50 60 70
y 10 20 50
20
Fancy Indexing in 2D
>>> a[(0,1,2,3,4),(1,2,3,4,5)]
array([ 1, 12, 23, 34, 45]) 0 1 2 3 4 5
10 11 12 13 14 15
>>> a[3:,[0, 2, 5]]
array([[30, 32, 35], 20 21 22 23 24 25
[40, 42, 45]])
[50, 52, 55]]) 30 31 32 33 34 35
40 41 42 43 44 45
>>> mask = array([1,0,1,0,0,1],
dtype=bool) 50 51 52 53 54 55
>>> a[mask,2]
array([2,22,52])
Unlike slicing, fancy indexing
creates copies instead of
views into original arrays.
21