Introduction to NumPy, Pandas, and Matplotlib
Introduction to NumPy Arrays
Advantages of NumPy Arrays
NumPy (Numerical Python) is a powerful library for numerical computing
in Python.
The core feature of NumPy is its ndarray (N-dimensional array), which
offers several advantages over Python’s built-in lists:
- Efficiency: NumPy arrays are stored in contiguous memory locations,
making operations faster compared to Python lists.
- Performance: NumPy operations are optimized using C and Fortran
libraries, leading to significantly faster computations.
- Convenient mathematical operations: NumPy supports element-wise
operations, matrix computations, and statistical functions.
- Less Memory Consumption: NumPy arrays consume less memory
compared to lists since they use a fixed type for elements.
- Vectorization: NumPy provides vectorized operations, eliminating the
need for explicit loops and improving performance.
Creation of NumPy Arrays
NumPy arrays can be created using different methods:
1. Creating an Array from a List:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
2. Creating Arrays with Zeros and Ones:
np.zeros((3,3)) # 3x3 array of zeros
np.ones((2,2)) # 2x2 array of ones
3. Creating an Array with a Range of Numbers:
np.arange(1, 10, 2) # [1 3 5 7 9]
4. Creating an Array with Evenly Spaced Numbers:
np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1. ]
5. Creating a Random Array:
np.random.rand(3,3) # 3x3 array with random numbers between 0 and 1
Computation on NumPy Arrays
Universal Functions (ufuncs)
NumPy provides universal functions (ufuncs), which perform fast element-
wise operations.
Broadcasting
Broadcasting allows NumPy to perform arithmetic operations on arrays of
different shapes.
Example:
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr + 10) # Adds 10 to each element
Fancy Indexing
Fancy indexing allows access to multiple array elements at once.
Example:
arr = np.array([10, 20, 30, 40, 50])
indices = [0, 2, 4]
print(arr[indices]) # [10 30 50]
Introduction to Pandas
Pandas Series
Pandas Series is a one-dimensional labeled array. It can be created from
arrays or dictionaries.
Example:
import pandas as pd
data = {'a': 10, 'b': 20, 'c': 30}
series = pd.Series(data)
print(series)
Pandas DataFrames
Pandas DataFrame is a two-dimensional labeled data structure.
Example:
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]}
df = pd.DataFrame(data)
print(df)
Introduction to Matplotlib
Basic Plotting
Matplotlib is a popular Python library for data visualization.
Example:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Basic Line Plot')
plt.show()