
116 views
NumPy Operations in Python
NumPy (Numerical Python) is a powerful library in Python that provides support for performing a wide range of mathematical and numerical operations on arrays and matrices. Here are some common NumPy operations in Python:
- Creating NumPy Arrays:
- NumPy provides functions like
numpy.array()
,numpy.zeros()
,numpy.ones()
, andnumpy.arange()
to create arrays.
Python
import numpy as np
# Create an array
arr = np.array([1, 2, 3, 4, 5])
# Create a 3x3 array of zeros
zeros_array = np.zeros((3, 3))
# Create a 2x3 array of ones
ones_array = np.ones((2, 3))
# Create an array of values from 0 to 4
range_array = np.arange(5)
- Array Operations:
- NumPy arrays support element-wise operations, making it easy to perform operations on entire arrays.
Python
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Element-wise addition
result_addition = arr1 + arr2 # [5, 7, 9]
# Element-wise multiplication
result_multiplication = arr1 * arr2 # [4, 10, 18]
- Array Indexing and Slicing:
- You can access and manipulate elements of a NumPy array using indexing and slicing.
Python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Accessing elements
element = arr[2] # 3
# Slicing
sub_array = arr[1:4] # [2, 3, 4]
- Array Shape and Reshaping:
- NumPy provides functions to get the shape of an array and to reshape arrays.
Python
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Get the shape of the array
shape = arr.shape # (2, 3)
# Reshape the array
reshaped = arr.reshape(3, 2)
- Array Aggregation:
- NumPy allows you to calculate statistics on arrays, such as mean, sum, minimum, and maximum.
Python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Calculate mean
mean = np.mean(arr) # 3.0
# Calculate sum
total = np.sum(arr) # 15
# Find minimum and maximum
min_value = np.min(arr) # 1
max_value = np.max(arr) # 5
- Matrix Operations:
- NumPy supports matrix operations like matrix multiplication and transpose.
Python
import numpy as np
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
# Matrix multiplication
result_matrix = np.dot(matrix1, matrix2)
# Matrix transpose
transposed_matrix = np.transpose(matrix1)
- Broadcasting:
- NumPy allows you to perform operations on arrays with different shapes through broadcasting.
Python
import numpy as np
arr = np.array([1, 2, 3])
# Broadcasting to add 10 to each element
result = arr + 10 # [11, 12, 13]
- Random Number Generation:
- NumPy provides functions to generate random numbers and arrays.
Python
import numpy as np
# Generate random numbers between 0 and 1
random_numbers = np.random.rand(3, 3)
# Generate random integers between 1 and 100
random_integers = np.random.randint(1, 101, size=(3, 3))
These are just a few examples of the many operations you can perform with NumPy. NumPy is an essential library for scientific computing and data analysis in Python, providing a wide range of tools for numerical computations.