Dimensions in Arrays

M3-R5.1 · Chapter 9: NumPy Basics · 16 min read

Dimensions in Arrays  :  A dimension in arrays is one level of array depth (nested arrays).

Nested array: are arrays that have arrays as their elements.

0-D Arrays :  0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.

Example Create a 0-D array with value 42

import numpy as np

arr = np.array(42)

print(arr)

1-D Arrays:  An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.these are the most common and basic arrays.

Example: Create a 1-D array containing the values 1,2,3,4,5:

                   import numpy as np

                  arr = np.array([1, 2, 3, 4, 5])

                  print(arr)

2-D Arrays :  An array that has 1-D arrays as its elements is called a 2-D array.these are often used to represent matrix or 2nd order tensors.

  • NumPy has a whole sub module dedicated towards matrix operations called numpy.mat

Example: Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

print(arr)

3-D arrays :  An array that has 2-D arrays (matrices) as its elements is called 3-D array.these are often used to represent a 3rd order tensor.

Example: Create a 3-D array with two 2-D arrays, both containing two arrays with the values 1,2,3 and 4,5,6:

import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(arr)                    

Check Number of Dimensions? : NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the array have.

Example: Check how many dimensions the arrays have:

import numpy as np

a = np.array(42)

b = np.array([1, 2, 3, 4, 5])

c = np.array([[1, 2, 3], [4, 5, 6]])

d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(a.ndim)

print(b.ndim)

print(c.ndim)

print(d.ndim)

Higher Dimensional Arrays: An array can have any number of dimensions. When the array is created, you can define the number of dimensions by using the ndmin argument.

Example: Create an array with 5 dimensions and verify that it has 5 dimensions:

import numpy as np

arr = np.array([1, 2, 3, 4], ndmin=5)

print(arr)

print('number of dimensions :', arr.ndim)

In this array the innermost dimension (5th dim) has 4 elements, the 4th dim has 1 element that is the vector, the 3rd dim has 1 element that is the matrix with the vector, the 2nd dim has 1 element that is 3D array and 1st dim has 1 element that is a 4D array.

NumPy Array Indexing

Access Array Elements: Array indexing is the same as accessing an array element. we can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

Example:  Get the first element from the following array:

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr[0])

Example: Get the second element from the following array.

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr[1])

Example: Get third and fourth elements from the following array and add them.

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr[2] + arr[3])

Access 2-D Arrays : To access elements from 2-D arrays we can use comma separated integers  representing

             the dimension and the index of the element.

         Think of 2-D arrays like a table with rows and columns, where the row represents the dimension and the        

          index represents the column.

Example: Access the element on the first row, second column:

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('2nd element on 1st row: ', arr[0, 1])

Example: Access the element on the 2nd row, 5th column:

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('5th element on 2nd row: ', arr[1, 4])

Access 3-D Arrays :  To access elements from 3-D arrays we can use comma separated integers representing the dimensions and the index of the element.

Example: Access the third element of the second array of the first array:

 import numpy as np

 arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

 print(arr[0, 1, 2])

 Explained :  arr[0, 1, 2] prints the value 6.

And this is why:

  • The first number represents the first dimension, which contains two arrays: [[1, 2, 3], [4, 5, 6]] and:

[[7, 8, 9], [10, 11, 12]] Since we selected 0, we are left with the first array: [[1, 2, 3], [4, 5, 6]]

  • The second number represents the second dimension, which also contains two arrays: [1, 2, 3] and: [4, 5, 6]
  • Since we selected 1, we are left with the second array: [4, 5, 6]
  • The third number represents the third dimension, which contains three values: 4 5 6 Since we selected 2, we end up with the third value: 6

:NumPy Array Slicing :

Slicing arrays : Slicing in python means taking elements from one given index to another given index.

  • We pass slice instead of index like this: [start:end].
  • We can also define the step, like this: [start:end:step].
  • If we don't pass start its considered 0
  • If we don't pass end its considered length of array in that dimension
  • If we don't pass step its considered 1

Example: Slice elements from index 1 to index 5 from the following array:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[1:5])                             OUTPUT: [2 3 4 5]

                       Note: The result includes the start index, but excludes the end index.

Example: Slice elements from index 4 to the end of the array:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[4:])                                           OUTPUT:  [5 6 7]

Example: Slice elements from the beginning to index 4 (not included):

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[:4])                                           OUTPUT:  [1 2 3 4]

Negative Slicing :Use the minus operator to refer to an index from the end:

Example: Slice from the index 3 from the end to index 1 from the end:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[-3:-1])

STEP :  Use the step value to determine the step of the slicing:

Example: Return every other element from index 1 to index 5:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[1:5:2])

Example: Return every other element from the entire array:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[::2])

Slicing 2-D Arrays

Example : From the second element, slice elements from index 1 to index 4 (not included):

import numpy as np

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(arr[1, 1:4])                                                                      OUTPUT:   [7 8 9]

Note: Remember that second element has index 1.

Example From both elements, return index 2:

import numpy as np

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(arr[0:2, 2])                                                           OUTPUT:   [3 8 ]

Example: From both elements, slice index 1 to index 4 (not included), this will return a 2-D array:

import numpy as np

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])                          OUTPUT:  [[2 3 4]

print(arr[0:2, 1:4])                                                                                             [7 8 9]]

NumPy arrays come with a variety of attributes that provide useful information about the array's structure and content. Here are some of the most commonly used attributes:

Make sure you have NumPy imported:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

Attribute

Description

Example Output

arr.ndim

Number of dimensions

2

arr.shape

Shape of the array (rows, columns)

(2, 3)

arr.size

Total number of elements

6

arr.dtype

Data type of the elements

dtype('int64') (may vary)

arr.itemsize

Size (in bytes) of each element

8

arr.nbytes

Total bytes consumed (size × itemsize)

48

arr.T

Transpose of the array

[[1 4], [2 5], [3 6]]

arr.data

Memory buffer (advanced use)

<memory at 0x...>

import numpy as np

arr = np.array([[10, 20, 30], [40, 50, 60]])

print("Dimensions:", arr.ndim)

print("Shape:", arr.shape)

print("Size:", arr.size)

print("Data type:", arr.dtype)

print("Item size:", arr.itemsize)

print("Total bytes:", arr.nbytes)

print("Transpose:\n", arr.T)

 

Data Types in NumPy

NumPy has some extra data types, and refer to data types with one character, like i for integers, u for unsigned integers etc. Below is a list of all data types in NumPy and the characters used to represent them.

  • i - integer
  • b - boolean
  • u - unsigned integer
  • f - float
  • c - complex float
  • m - timedelta
  • M - datetime
  • - object
  • S - string
  • U - unicode string
  • V - fixed chunk of memory for other type ( void )

Checking the Data Type of an Array : The NumPy array object has a property called dtype that returns the data type of the array:

     Example: Get the data type of an array object:

import numpy as np

arr = np.array([1, 2, 3, 4])

 print(arr.dtype)                                          OUTPUT:  int64

   Example: Get the data type of an array containing strings:

import numpy as np

 arr = np.array(['apple', 'banana', 'cherry'])

 print(arr.dtype)                                                                        OUTPUT:   <U6

NumPy Array Functions

NumPy array functions are the built-in functions provided by NumPy that allow us to create and manipulate arrays, and perform different operations on them.There are  some of the most commonly used NumPy array functions.

There are many NumPy array functions available but here are some of the most commonly used ones.

Array Operations

Functions

  • Array Creation Functions

np.array(), np.zeros(), np.ones(), np.empty(), etc.

  • Array Manipulation Functions

np.reshape(), np.transpose(), etc

  • Array Mathematical Functions

np.add(), np.subtract(), np.sqrt(), np.power(), etc.

  • Array Statistical Functions

np.median(), np.mean(), np.std(), and np.var().

  • Array Input and Output Functions

np.save(), np.load(), np.loadtxt(), etc.

NumPy Array Creation Functions:    Array creation functions allow us to create new NumPy arrays.

Example:

import numpy as np

array1 = np.array([1, 3, 5])     # create an array using np.array()

print("np.array():\n", array1)

OUTPUT

np.array():

(1 3 5)

# create an array filled with zeros using np.zeros()

array2 = np.zeros((3, 3))

print("\nnp.zeros():\n", array2)

np.zeros():

[[0,0,0]

[0,0,0]

[0,0,0]]

# create an array filled with ones using np.ones()

array3 = np.ones((2, 4))

print("\nnp.ones():\n", array3)

np.ones():

[[1,1,1,1]

[1,1,1,1]

      [1,1,1,1]]

                    Here:

  • np.array() - creates an array from a Python List
  • np.zeros() - creates an array filled with zeros of the specified shape
  • np.ones() - creates an array filled with ones of the specified shape

 NumPy Array Manipulation Functions: NumPy array manipulation functions allow us to modify or rearrange NumPy arrays.

    Example:

import numpy as np

array1 = np.array([1, 3, 5, 7, 9, 11])  # create a 1D array

# reshape the 1D array into a 2D array

array2 = np.reshape(array1, (2, 3))

# transpose the 2D array

array3 = np.transpose(array2)

print("Original array:\n", array1)

print("\nReshaped array:\n", array2)

print("\nTransposed array:\n", array3)

            :OUTPUT:

Original array:

          [1 3 5 7 9 11]

Reshaped array:

        [[1 3 5]

        [ 7 9 11]]

Reshaped array:

          [[1  7]

          [ 3  9 ]

          [ 5  11 ]]

In the Above example:

  • np.reshape (array1, (2, 3)) - reshapes array1 into 2D array with shape (2,3)
  • np.transpose(array2) - transposes 2D array array2

NumPy Array Mathematical Functions : In NumPy, there are tons of mathematical functions to perform on arrays.

            Example:

import numpy as np

# create two arrays

         array1 = np.array([1, 2, 3, 4, 5])

         array2 = np.array([4, 9, 16, 25, 36])

# add the two arrays element-wise

        arr_sum = np.add(array1, array2)

# subtract the array2 from array1 element-wise

          arr_diff = np.subtract(array1, array2)

# compute square root of array2 element-wise

         arr_sqrt = np.sqrt(array2)

         print("\nSum of arrays:\n", arr_sum)

         print("\nDifference of arrays:\n", arr_diff)

         print("\nSquare root of first array:\n", arr_sqrt)

    :OUTPUT:

Sum of arrays:

        [ 5  11  19   29   41 ]

Difference of arrays:

       [ -3    -7   -13   -21   -31 ]

Square root of first array:

    [ 2,    3,   4,   5,   6 ]

NumPy Array Statistical Functions :  NumPy provides us with various statistical functions to perform statistical data analysis. These statistical functions are useful to find basic statistical concepts like mean, median, variance, etc. It is also used to find the maximum or the minimum element in an array.

Example:

import numpy as np

# create a numpy array

            marks = np.array([76, 78, 81, 66, 85])

# compute the mean of marks

            mean_marks = np.mean(marks)

             print("Mean:",mean_marks)

# compute the median of marks

            median_marks = np.median(marks)

             print("Median:",median_marks)

# find the minimum and maximum marks

                 min_marks = np.min(marks)

                  print("Minimum marks:", min_marks)

                 max_marks = np.max(marks)

                   print("Maximum marks:", max_marks)

:OUTPUT:

Mean:  77.2

Median:78.0

Minimum marks:66

Maximum marks:85

NumPy Array Input/output Functions: NumPy offers several input/output (I/O) functions for loading and saving data to and from files.

Example:

import numpy as np

# create an array

array1 = np.array([[1, 3, 5], [2, 4, 6]])

# save the array to a text file

np.savetxt('data.txt', array1)

# load the data from the text file

loaded_data = np.loadtxt('array1.txt')

# print the loaded data

print(loaded_data)

:OUTPUT:

 [ [1, 3, 5]

  [2, 4, 6, ] ]