Indexing and slicing
Indexing and slicing allow you to access specific elements of an array - it is important to understand how this works for arrays of varying dimensions. Important to remember is that python is zero-indexed i.e. the first position in a list, an array or any other data structure has an index of zero.
Let’s start by making a simple array of random numbers:
The best way to think about slicing an array is to imagine a syntax structure of
array[start_slice:end_slice:step] (where not all of the variables (start_slice, end_slice, step) need to be set).
To get the first value of the array by index, type:
To get the first 3 values of the array
rand by index, type:
To take a slice, accessing all values:
To take a slice and get all but the last value:
To reverse the array:
To get every second value:
All of the above can be assigned to a variable - it is worth taking notice the type of object that is created according to what is returned by the index/slice:
numpy.dtype(skip) on this second example - why don’t you think it works? If you’re not sure, check the function documentation.
Let’s start by making a 2-dimensional random array:
Indexing in multiple dimensions is the same as for 1-dimension, except that your slice statements are specified per dimension. Accessing the dimensions of an array can be visualised as:
1-dimension: array[1st_dimension] 2-dimensions: array[1st_dimension,2nd_dimension] 3-dimensions: array[1st_dimension,2nd_dimension,3rd_dimension]
To access all elements of the 1st dimension (you can imagine this as the top row):
To access all elements of the 1st 2 dimensions (you can imagine this as the top 2 rows):
To access the first element of each dimension (you can imagine this as the 1st column):
To access the first 2 elements of each dimension (you can imagine this as the 2 columns):