NumPy

NumPy is a powerful library for numerical computing in Python. It provides efficient and flexible tools for working with arrays, performing mathematical computations, and generating data.

Key Features

1. Array Creation: NumPy provides the ndarray object, which is a fast and space-efficient multidimensional array for storing data.
import numpy as np
# Create a 1D array
array_1d = np.array([1, 2, 3, 4])

# Create a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])

# Print the arrays
print("1D Array:", array_1d)
print("2D Array:\n", array_2d)
2. Array Attributes: You can access array properties such as shape, size, and data type.
print("Shape:", array_2d.shape)  # (2, 3)
print("Size:", array_2d.size)    # 6
print("Data Type:", array_2d.dtype)  # int32 (or int64 depending on platform)
3. Mathematical Operations NumPy supports element-wise operations and broadcasting (applying operations on arrays of different shapes).
# Element-wise addition and multiplication
result = array_2d + 10
product = array_2d * 2

print("Addition:\n", result)
print("Multiplication:\n", product)
4. Statistical Functions
# Generate a random array
random_array = np.random.randint(1, 10, size=10)

# Calculate statistics
mean = np.mean(random_array)
std = np.std(random_array)
sum_array = np.sum(random_array)

print("Array:", random_array)
print("Mean:", mean, "Std Dev:", std, "Sum:", sum_array)
5. Indexing and Slicing: Access and modify specific elements or subarrays.
# Access elements
print("Element at (0, 1):", array_2d[0, 1])  # 2

# Slice rows and columns
print("First row:", array_2d[0, :])  # [1, 2, 3]
print("Second column:", array_2d[:, 1])  # [2, 5]
6. Sample Data Generation: NumPy provides functions for generating arrays for testing and experimentation.
  • Random Numbers: Generate random integers, floats, or arrays.
  • Linspace: Create evenly spaced numbers over a specified range.
  • Arange: Generate sequences of numbers with a specified step size.
# Random integers
random_ints = np.random.randint(1, 100, size=(3, 3))

# Linearly spaced array
linear_space = np.linspace(0, 1, 5)

# Sequence of numbers
sequence = np.arange(0, 10, 2)

print("Random Integers:\n", random_ints) # Outputs a 3x3 array of random integers
print("Linearly Spaced Array:", linear_space) # [0. 0.25 0.5 0.75 1.]
print("Sequence of Numbers:", sequence) # [0 2 4 6 8]
7. Matrix Operations
# Dot product
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
dot_product = np.dot(A, B)

# Transpose
transpose = A.T

# Inverse (requires square matrix)
inverse = np.linalg.inv(A)

print("Dot Product:\n", dot_product)
print("Transpose:\n", transpose)
print("Inverse:\n", inverse)