NumPy is a fundamental library for numerical 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.
12.1 What is NumPy?
NumPy stands for Numerical Python and is used for performing mathematical operations on large arrays and matrices. It offers a powerful array object and functions for performing operations on these arrays efficiently.
12.2 Installing NumPy
To install NumPy, use the following pip command:
pip install numpy
12.3 Basic Operations with NumPy
Here are some basic operations you can perform with NumPy:
12.3.1 Creating Arrays
import numpy as np
# Creating a NumPy array
arr = np.array([1, 2, 3, 4, 5])
print(arr)
12.3.2 Array Operations
NumPy arrays support element-wise operations:
# Array addition
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
sum_arr = arr1 + arr2
print(sum_arr)
# Array multiplication
product_arr = arr1 * arr2
print(product_arr)
12.3.3 Array Reshaping
You can reshape arrays using NumPy:
# Reshape an array
arr = np.arange(12) # Create an array with values 0-11
reshaped_arr = arr.reshape((3, 4))
print(reshaped_arr)
12.4 Using NumPy with Pandas
NumPy arrays can be used in conjunction with Pandas DataFrames for more efficient computations:
import pandas as pd
import numpy as np
# Create a DataFrame with NumPy arrays
data = {
'A': np.array([1, 2, 3]),
'B': np.array([4, 5, 6])
}
df = pd.DataFrame(data)
print(df)
Comments
Post a Comment