Slicing

Arrays can be sliced just like lists and tuples. Array slicing is identical to list slicing, except that the syntax is simpler. Arrays are sliced using the [ : , :, ... :] syntax, where the number of dimensions of the arrays determine the size of the slice, except that these dimensions for which slices are omitted, all elements are selected. For example, if b is a three-dimensional array, b[0:2] is the same as b[0:2,:,:]. There are shorthand notations for slicing. Some common ones are:

  • : and: are the same as 0:n:1, where n is the length of the array
  • m: and m:n: are the same as m:n:1, where n is the length of the array
  • :n: is the same as 0:n:1
  • ::d: is the same as 0:n:d, where n is the length of the array

All these slicing methods have been referenced with the usage of arrays. This can also be applicable to lists. Slicing of one-dimensional arrays is identical to slicing a simple list (as one-dimensional arrays can be seen equivalent to a list), and the returned type of all the slicing operations matches the array being sliced. The following is a simple mechanism that shows array slices:

x = array([5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])

# interpret like this – default start but end index is 2
y = x[:2]
array([5, 6])

# interpretation – default start and end, but steps of 2
y = x[::2]
array([5,7,9,11,13,15,17,19])

NumPy attempts to convert data type automatically if an element with one data type is inserted into an array with a different data type. For example, if an array has an integer data type, place a float into the array results in the float being truncated and store it as an integer. This can be dangerous; therefore in such cases, arrays should be initialized to contain floats unless a considered decision is taken to use a different data type for a good reason. This example shows that even if one element is float and the rest is integer, it is assumed to be the float type for the benefit of making it work properly:

a = [1.0, 2,3,6,7]
b = array(a)

b.dtype
dtype('float64')

Slice using flat

Data in matrices are stored in a row-major order, which means elements are indexed first by counting along the rows and then down the columns. For example, in the following matrix, there are three rows and three columns; the elements are read in the order 4,5,6,7,8,9,1,2,3 (for each row, column-wise):

Slice using flat

Linear slicing assigns an index to each element of the array in the order of the elements read. In two-dimensional arrays or lists, linear slicing works by first counting across the rows and then down the columns. In order to use linear slicing, you have to use the flat function, as shown in the following code:

a=array([[4,5,6],[7,8,9],[1,2,3]])
b = a.flat[:]

print b
[4, 5, 6, 7, 8, 9, 1, 2, 3]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset