Mastering NumPy Arrays

Mastering NumPy Arrays

NumPy is a powerful library for numerical computing in Python, offering robust support for large, multi-dimensional arrays and an extensive collection of mathematical functions.

Creating Arrays

To begin using NumPy, import the library and create arrays:

import numpy as np

# 1D array (Similar to a list.)
array_1d = np.array([1, 2, 3])
print(array_1d)  # Output: [1 2 3]

# 2D array(Similar to a table.)
array_2d = np.array([(1, 2, 3), (4, 5, 6)])
print(array_2d)  # Output: [[1 2 3] [4 5 6]]

# 3D array(Similar to two tables)
array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(array_3d)  # Output: [[[1 2] [3 4]] [[5 6] [7 8]]]

Special Arrays

Create arrays filled with zeros(), ones(), full().

# Array of zeros
print(np.zeros((3, 2)))  # Output: [[0 0] [0 0] [0 0]]

# Array of ones
print(np.ones((2, 2)))  # Output: [[1 1] [1 1]]

# Array filled with a specific value
print(np.full((5, 3), 8))  # Output: [[8 8 8] [8 8 8] [8 8 8] [8 8 8] [8 8 8]]

Array attributes

NumPy arrays have several attributes that enable you to access information about the array. Some of the most commonly used attributes include the following:

  • ndarray.shape: returns a tuple of the array’s dimensions.

  • ndarray.dtype: returns the data type of the array’s contents.

  • ndarray.size: returns the total number of elements in the array.

  • ndarray.T: returns the array transposed rows becomes columns, columns become rows).

  •       array = np.array([(1, 2, 3), (4, 5, 6)])
          print(array )# Output:  [ [1 2 3] [4 5 6] ]
          print(array.shape)# Output: (2, 3)
          print(array.dtype)# Output: int64
          print(array.size)# Output: 6
          print(array.T)# Output:[ [1 4] [2 5] [3 6]]
    

Array Methods

Some important array methods are flatten() , reshape(), and tolist().

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

# Flatten an array( returns a copy of the array collapsed into one dimension.)
print(array .flatten())  # Output: [1 2 3 4 5 6]

# Reshape an array( Gives a new shape to an array without changing its data.)
print(array .reshape(3, 2))  # Output: [[1 2] [3 4] [5 6]]

# Reshape with inferred dimension
print(array .reshape(3, -1))  # Output: [[1 2] [3 4] [5 6]]

# Convert array to list(Converts an array to a list object.) 
print(array .tolist())  # Output: [[1, 2, 3], [4, 5, 6]]

Mathematical Functions

Some common mathematical operations : max(), mean(), min(), std().

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

# Maximum value
print(array .max())  # Output: 6

# Mean value
print(array .mean())  # Output: 3.5

# Minimum value
print(array .min())  # Output: 1

# Standard deviation
print(array .std())  # Output: 1.707825127659933

Indexing and Slicing

  • Access individual elements of a NumPy array using indexing and slicing.

  • Indexing in NumPy is similar to indexing in Python lists, except multiple indices can be used to access elements in multidimensional arrays.

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

# Indexing
print(array [1])  # Output: [4 5 6]
print(array [0, 1])  # Output: 2
print(array [1, 2])  # Output: 6

# Slicing to access subarrays of a NumPy array
print(array [:, 1:])  # Output: [[2 3] [5 6]]

Array Operations

NumPy arrays support a variety of operations, including mathematical functions and arithmetic, such as element-wise addition and multiplication.

a = np.array([(1, 2, 3), (4, 5, 6)])
b = np.array([[1, 2, 3], [1, 2, 3]])
print(a)         # Output: [[1 2 3] [4 5 6]]
print(b)         # Output: [[1 2 3] [1 2 3]]
print(a + b)     # Output: [[2 4 6] [5 7 9]]
print(a * b)     # Output: [[ 1  4  9] [ 4 10 18]]

Furthermore, there are other crucial mathematical functions that can be applied to individual or multiple arrays.

Mutability

NumPy arrays are mutable, though they have certain limitations. For example, you can modify an existing element in an array:

# Modify an element
a[1][1] = 100
print(a)  # Output: [[  1   2   3] [  4 100   6]]

# Attempt to add an element (will cause an error)
a[3] = 100  # Uncommenting this will raise an IndexError

To conclude, NumPy arrays allocate a contiguous block of memory, ensuring fast access and manipulation but restricting the ability to resize after creation.

By mastering these core functionalities, you can leverage NumPy arrays for efficient numerical computing and data manipulation in your projects. Save this guide for quick reference and further practice as you delve deeper into data science and numerical analysis with NumPy.