![]() |
VOOZH | about |
Indexing in multi-dimensional arrays allows us to access, modify or extract specific elements or sections from arrays efficiently. In Python, NumPy provides tools to handle this through index numbers, slicing and reshaping.
The np.arange() function is used to create a one-dimensional NumPy array containing evenly spaced values within a specified range.
Syntax
np.arange( [start, ] stop [, step,], dtype=None )
Parameters:
Example: Here we use np.arange() to create a 1D array containing a sequence of numbers from 0 to 4.
[0 1 2 3 4]
The np.arange() function can generate a sequence by explicitly defining the start, stop and step values to control how the numbers are spaced in the array.
[20 22 24 26 28]
Explanation: Starts at 20, ends before 30 and 2 is the step it skips one number each time.
Elements in a NumPy array can be accessed directly using index positions or groups of elements can be extracted using slicing ranges.
[20 22 24 26 28] 24 [22 24 26]
Explanation:
We use reshape() with arange() to convert a 1D array into a 2D array.
[[ 0 1] [ 2 3] [ 4 5] [ 6 7] [ 8 9] [10 11]]
Explanation:
The reshape() function in NumPy converts an existing array into a new shape specified by the user. It is often used with np.arange() to quickly generate structured multi-dimensional arrays.
Syntax
numpy.reshape(a, newshape)
Parameters:
We can also reshape arrays into 3D arrays by specifying the required shape.
[[[ 0 1 2] [ 3 4 5]] [[ 6 7 8] [ 9 10 11]]]
Explanation:
Specific elements or sections of a multidimensional array can be retrieved by applying slices along each dimension to access the desired data subset.
[[[ 0 1 2] [ 3 4 5]] [[ 6 7 8] [ 9 10 11]]] [[[6 7 8]]]
Explanation: