Code
import numpy as np
NumPy is a powerful Python library for numerical computing. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays efficiently. This tutorial introduces the basics of NumPy for beginners, with additional sections on advanced features and integration with other libraries.

pip install numpy)pip install pandas matplotlib)NumPy (Numerical Python) is the foundation for many scientific and data analysis libraries in Python, such as Pandas, SciPy, and Matplotlib. It is optimized for performance, using efficient array operations implemented in C.
First, import NumPy in your Python script or notebook:
The alias np is a common convention to make code shorter.
NumPy arrays (ndarray) are the core data structure. Here are common ways to create them:
# Array of zeros
zeros = np.zeros((2, 3)) # 2 rows, 3 columns
print(zeros)
# Output:
# [[0. 0. 0.]
# [0. 0. 0.]]
# Array of ones
ones = np.ones((3, 2))
print(ones)
# Output:
# [[1. 1.]
# [1. 1.]
# [1. 1.]]
# Array with a range of values
range_arr = np.arange(0, 10, 2) # Start, stop, step
print(range_arr) # Output: [0 2 4 6 8]
# Evenly spaced values
linspace_arr = np.linspace(0, 1, 5) # 5 values from 0 to 1
print(linspace_arr) # Output: [0. 0.25 0.5 0.75 1. ]NumPy arrays have attributes to inspect their properties:
NumPy supports element-wise operations and broadcasting, making calculations intuitive.
Access elements in a NumPy array similar to Python lists, but with more flexibility for multi-dimensional arrays.
Change the shape of an array without altering its data:
Note: The total number of elements must remain the same (e.g., 6 elements can be reshaped into 2x3 or 3x2).
NumPy provides functions to compute statistics:
Generate random numbers for simulations or testing:
# Random array of shape (2, 3) with values between 0 and 1
rand_arr = np.random.rand(2, 3)
print(rand_arr)
# Example Output:
# [[0.12345678 0.98765432 0.45678901]
# [0.78912345 0.32165498 0.65432109]]
# Random integers between 1 and 10
rand_int = np.random.randint(1, 10, size=(2, 2))
print(rand_int)
# Example Output:
# [[7 3]
# [9 1]]Save arrays to disk and load them later:
NumPy offers powerful features for advanced data manipulation and computation.
Broadcasting allows NumPy to perform operations on arrays of different shapes by automatically expanding smaller arrays to match the shape of larger ones.
Masking uses boolean arrays to filter elements based on conditions.
NumPy provides functions for linear algebra operations, such as matrix multiplication, dot products, and solving linear systems.
# Matrix multiplication
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
result = np.dot(A, B)
print(result)
# Output:
# [[19 22]
# [43 50]]
# Inverse of a matrix
inv_A = np.linalg.inv(A)
print(inv_A)
# Output:
# [[-2. 1. ]
# [ 1.5 -0.5]]
# Solve linear system Ax = b
b = np.array([1, 2])
x = np.linalg.solve(A, b)
print(x) # Output: [-1. 1.]The np.where function allows conditional operations on arrays, returning elements based on a condition or applying different values.
arr = np.array([10, 15, 20, 25, 30])
# Replace values > 20 with 100, else keep original
result = np.where(arr > 20, 100, arr)
print(result) # Output: [ 10 15 20 100 100]
# Get indices where condition is true
indices = np.where(arr > 20)
print(indices) # Output: (array([3, 4]),)
print(arr[indices]) # Output: [25 30]The np.concatenate function joins arrays along a specified axis.
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
# Concatenate along rows (axis=0)
result_rows = np.concatenate((arr1, arr2), axis=0)
print(result_rows)
# Output:
# [[1 2]
# [3 4]
# [5 6]
# [7 8]]
# Concatenate along columns (axis=1)
result_cols = np.concatenate((arr1, arr2), axis=1)
print(result_cols)
# Output:
# [[1 2 5 6]
# [3 4 7 8]]The np.fft module provides Fast Fourier Transform (FFT) functions for signal processing.
The np.vstack function stacks arrays vertically (row-wise), meaning it stacks them as rows in a single array. The arrays must have the same shape along all but the first axis.
The np.hstack function stacks arrays horizontally (column-wise), meaning it stacks them as columns in a single array. The arrays must have the same shape along all but the second axis.
The np.unique function returns the sorted unique elements of an array. It can also return indices and counts of occurrences.
NumPy integrates seamlessly with Pandas for data analysis and Matplotlib for visualization.
Pandas builds on NumPy to provide data structures like DataFrames for tabular data.
import pandas as pd
# Create a NumPy array
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df = pd.DataFrame(data, columns=['A', 'B', 'C'])
print(df)
# Output:
# A B C
# 0 1 2 3
# 1 4 5 6
# 2 7 8 9
# Compute column means using NumPy
means = np.mean(df, axis=0)
print(means)
# Output:
# A 4.0
# B 5.0
# C 6.0
# dtype: float64Matplotlib uses NumPy arrays to create visualizations like plots and charts.
Let’s combine concepts in a small example:
# Simulate monthly temperatures
temps = np.random.randint(20, 35, size=12)
print("Monthly Temperatures:", temps)
print("Average Temperature:", np.mean(temps))
print("Hottest Month:", np.max(temps))
print("Coldest Month:", np.min(temps))
# Visualize with Matplotlib
months = np.arange(1, 13)
plt.bar(months, temps)
plt.title('Monthly Temperatures')
plt.xlabel('Month')
plt.ylabel('Temperature (°C)')
plt.show()This tutorial has covered the essentials of NumPy for beginners: - Basics: Creating arrays, attributes, and basic operations. - Manipulation: Indexing, slicing, reshaping, and aggregation. - Advanced Features: Broadcasting, masking, linear algebra, and functions like np.where, np.concatenate, np.fft, np.vstack, np.hstack, and np.unique. - Integration: Working with Pandas for data analysis and Matplotlib for visualization. - Practical Example: A simple data analysis workflow.
These concepts form the foundation for efficient numerical computing in Python.
NumPy is an indispensable tool for anyone working with numerical data in Python. By mastering these basics and advanced techniques, you’ll be well-equipped to tackle complex data science, machine learning, and scientific computing projects. Remember, practice is key—experiment with the examples, modify them, and build your own applications. The NumPy community is vibrant and supportive; don’t hesitate to explore further!