11.1 NumPy: Scientific Computing

11.1 NumPy: Scientific Computing

An introduction to NumPy, the fundamental library for scientific computing, and the powerful array object it provides.

NumPy (Numerical Python) is the fundamental library for scientific computing in Python. It provides a powerful multi-dimensional array object, as well as tools for working with these arrays. It is the foundation for many other data science libraries, such as Pandas and Matplotlib.

Key Features of NumPy:

  • N-dimensional arrays (ndarray): NumPy's central object, the `ndarray`, is a fast and efficient array for storing homogeneous data (i.e., all elements must be of the same type, e.g., all integers or all floats). This allows NumPy to store and process data much more efficiently than standard Python lists.
  • Fast Mathematical Operations (Vectorization): NumPy performs operations on entire arrays at once (a process called vectorization), instead of iterating over each element individually as a Python list would. This "under the hood" is written in optimized, compiled code (C and Fortran), making numerical operations extremely fast.
  • Linear Algebra Tools: It provides a full set of linear algebra functions, support for Fourier transforms, and advanced random number capabilities.
# import numpy as np # Common import convention

# # Creating a NumPy array
# my_array = np.array([1, 2, 3, 4, 5])
# print(f"My array: {my_array}")
# print(f"Array type: {type(my_array)}")
# print(f"Array shape: {my_array.shape}")

# # Array operations (vectorization)
# array_a = np.array([1, 2, 3])
# array_b = np.array([4, 5, 6])
# sum_array = array_a + array_b # Element-wise addition
# print(f"Sum of arrays: {sum_array}")

# # Two-dimensional array
# matrix = np.array([[1, 2, 3], [4, 5, 6]])
# print(f"Matrix:\n{matrix}")
# print(f"Matrix shape: {matrix.shape}")

print("The NumPy code is commented out. To run it, install NumPy locally ('pip install numpy').")
print("NumPy provides fast arrays for scientific computing.")

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.