Prev: Array indexing       |       Next: Array operations

# Array slicing¶

• Slicing also works following the same ideas and notation presented in lists.
• Slices create views (no copies) of the original array: slices produce 'views' of the array, which essenatially means different perspectives on data arangement.
• So, be careful: if you assign new values in a sliced array you actually assign new values to the original. If this is not the behavior you intended for, consider constructing a copy of the original array first.

#### 1D array¶

In [1]:
import numpy as np
ar = np.linspace(0,10,8, False)
print(ar, '\n')

print(ar[::-1])
print(ar[1:len(ar):2])

[ 0.    1.25  2.5   3.75  5.    6.25  7.5   8.75]

[ 8.75  7.5   6.25  5.    3.75  2.5   1.25  0.  ]
[ 1.25  3.75  6.25  8.75]

• View vs. copy
In [2]:
import numpy as np
ar = np.linspace(0,10,8, False)
print(ar, '\n')

# Assigniment of slice member is reflected on the original array
br = ar[::-1]
br[0]=100
print(br)
print(ar)

[ 0.    1.25  2.5   3.75  5.    6.25  7.5   8.75]

[ 100.      7.5     6.25    5.      3.75    2.5     1.25    0.  ]
[   0.      1.25    2.5     3.75    5.      6.25    7.5   100.  ]

In [3]:
# Construct a new array by calling copy()
import numpy as np
ar = np.linspace(0,10,8, False)
print(ar, '\n')

cr = ar.copy()[::-1]
cr[0]=100
print(cr)
print(ar)

[ 0.    1.25  2.5   3.75  5.    6.25  7.5   8.75]

[ 100.      7.5     6.25    5.      3.75    2.5     1.25    0.  ]
[ 0.    1.25  2.5   3.75  5.    6.25  7.5   8.75]


#### 2D array¶

• Slicing in 2D arrays works by independently setting the slices for each axis
In [4]:
import numpy as np
ar = np.arange(1,21).reshape(5,4)
ar

Out[4]:
array([[ 1,  2,  3,  4],
[ 5,  6,  7,  8],
[ 9, 10, 11, 12],
[13, 14, 15, 16],
[17, 18, 19, 20]])
In [5]:
ar[0,::2]

Out[5]:
array([1, 3])
In [6]:
ar[::2,:2]

Out[6]:
array([[ 1,  2],
[ 9, 10],
[17, 18]])
In [7]:
ar[2:5,2:4]

Out[7]:
array([[11, 12],
[15, 16],
[19, 20]])
In [8]:
ar[::2,::2]

Out[8]:
array([[ 1,  3],
[ 9, 11],
[17, 19]])

#### 3D array¶

In [9]:
import numpy as np
ar = np.arange(1,17).reshape(2,2,4)
print(ar)

[[[ 1  2  3  4]
[ 5  6  7  8]]

[[ 9 10 11 12]
[13 14 15 16]]]

In [10]:
ar[:,0,1:3]

Out[10]:
array([[ 2,  3],
[10, 11]])
In [11]:
ar[:,:,0:4:2]

Out[11]:
array([[[ 1,  3],
[ 5,  7]],

[[ 9, 11],
[13, 15]]])
In [12]:
ar[::-1,::-1,::-1]

Out[12]:
array([[[16, 15, 14, 13],
[12, 11, 10,  9]],

[[ 8,  7,  6,  5],
[ 4,  3,  2,  1]]])

## Slice with assignment¶

• Slicing combined with assignment is a flexible way to change array values. It will operate under the same restrictions as general array assignment, namely:
• Array homogeneity, and
In [13]:
import numpy as np
ar = np.linspace(0,10,8, False)
print(ar, '\n')

ar[2:5] = [1]                   # Works OK

# ar[2:5] = 'X'                 # Does NOT: 'X' can not be converted to integer

ar[2:5] = [100,200,300]         # Works OK: arrays broadcast

# ar[2:5] = [100,200]           # Does NOT: arrays do not broadcast

ar

[ 0.    1.25  2.5   3.75  5.    6.25  7.5   8.75]


Out[13]:
array([   0.  ,    1.25,  100.  ,  200.  ,  300.  ,    6.25,    7.5 ,
8.75])
In [14]:
import numpy as np
ar = np.arange(1,21).reshape(5,4)
print(ar,'\n')

ar[::2,:2] = '100'            # Works OK
print(ar)

[[ 1  2  3  4]
[ 5  6  7  8]
[ 9 10 11 12]
[13 14 15 16]
[17 18 19 20]]

[[100 100   3   4]
[  5   6   7   8]
[100 100  11  12]
[ 13  14  15  16]
[100 100  19  20]]

In [15]:
import numpy as np
ar = np.arange(1,21).reshape(5,4)
print(ar[::2,:2],'\n')

ar[::2,:2] = [100,200]            # Works OK
print(ar[::2,:2])                 # Works OK because slice and array value broadcast
print('\n',ar)

[[ 1  2]
[ 9 10]
[17 18]]

[[100 200]
[100 200]
[100 200]]

[[100 200   3   4]
[  5   6   7   8]
[100 200  11  12]
[ 13  14  15  16]
[100 200  19  20]]

In [16]:
import numpy as np
ar = np.arange(1,21).reshape(5,4)
print(ar,'\n')

ar[::2,:2] = [100,200,300]            #Does NOT work: slice and array value do not broadcast

[[ 1  2  3  4]
[ 5  6  7  8]
[ 9 10 11 12]
[13 14 15 16]
[17 18 19 20]]


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-4bfcc1d7a60e> in <module>()
3 print(ar,'\n')
4
----> 5 ar[::2,:2] = [100,200,300]            #Does NOT work: slice and array value do not broadcast

ValueError: could not broadcast input array from shape (3) into shape (3,2)

. Free learning material
. See full copyright and disclaimer notice