Numpy (Gemini)
NumPy is a fundamental package for scientific computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays.
Key Features:
ndarray:
The core of NumPy is the ndarray object, which represents a homogeneous, multi-dimensional array.
Array Creation:
NumPy offers various ways to create arrays:
np.array(): Creates an array from a list or tuple.
np.zeros(): Creates an array filled with zeros.
np.ones(): Creates an array filled with ones.
np.arange(): Creates an array with a sequence of numbers.
np.random.rand(): Creates an array with random numbers between 0 and 1.
np.random.randint(): Creates an array with random integers within a specified range.
Array Operations:
NumPy allows element-wise operations on arrays:
Arithmetic: +, -, *, /
Mathematical functions: np.sin(), np.cos(), np.exp(), np.sqrt()
Array Manipulation:
NumPy provides functions for reshaping, concatenating, and slicing arrays.
reshape(): Changes the shape of an array.
concatenate(): Joins arrays along a specified axis.
Slicing: Accessing parts of an array using indices.
Universal Functions (ufunc):
NumPy includes a wide range of mathematical functions that operate element-wise on arrays.
Broadcasting:
NumPy allows arithmetic operations between arrays of different shapes, where smaller arrays are "broadcast" to match the shape of larger arrays.
Example:
import numpy as np
# Create arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Element-wise addition
c = a + b
print(c) # Output: [5 7 9]
# Mathematical function
d = np.sqrt(a)
print(d) # Output: [1. 1.41421356 1.73205081]
# Reshape an array
e = np.arange(12).reshape(3, 4)
print(e)
# Output:
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]