Introduction to NumPy Arrays

Let's delve into Python's NumPy library and focus on the centerpiece of NumPy - arrays. NumPy, an acronym for 'Numerical Python', specializes in efficient computations on arrays. Arrays in NumPy are more efficient than typical Python data structures.

Meet NumPy

The power of NumPy lies in its fast computations on large data arrays, making it crucial in data analysis. Before we start, let's import it:

# Import NumPy as 'np' in Python
import numpy as np

np is a commonly used representation for numpy.

Understanding NumPy Arrays

NumPy arrays, like a sorted shopping list, allow for swift computations. Arrays offer quick access to elements. Let's create a simple one-dimensional NumPy array:

# Creating a one-dimensional (1D) numpy array
array_1d = np.array([1, 2, 3, 4, 5])
print(array_1d)  # prints: [1 2 3 4 5]

This code creates a five-element array.

Creating Multi-Dimensional Arrays

We can create multi-dimensional arrays as much as we would with a multi-day shopping list. Here, each sublist [] forms a row in the final array:

# Two-dimensional (2D) numpy array
array_2d = np.array([[1, 2, 3],[4, 5, 6]])
print(array_2d) 
'''prints:
[[1 2 3]
 [4 5 6]]
'''

Each row in the output corresponds to a sublist in the input list.

We can apply the same principle to create a three-dimensional array:

# Three-dimensional (3D) numpy array
array_3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(array_3d)
'''prints:
[[[ 1  2  3]
  [ 4  5  6]]

 [[ 7  8  9]
  [10 11 12]]]
'''
Arrays Properties: Size

NumPy arrays come with a series of built-in properties that give helpful information about the structure and type of data they hold. These are accessible via the size, shape, and type fields, respectively.

Let's start with size. This property indicates the total number of elements in the array. Elements can be numbers, strings, etc. This becomes especially useful when working with multi-dimensional arrays where manually counting elements can be tedious.

array_3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print("Size:", array_3d.size)  # Size: 12

The array above is a 3D array that contains two 2D arrays. Each of the 2D arrays has two arrays, and each of those has three elements. Therefore, the total number of elements is 2 * 2 * 3 = 12.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal