Libraries
Like I mentioned in the previous lesson, you won’t get very far without external libraries.
Here, we’ll learn the basics of three libraries that every data programmer needs to know:
- NumPy: A fundamental Python library for numerical computing that provides support for large, multi-dimensional arrays and matrices.
- Pandas: A data manipulation library that provides data structures for efficiently storing and analyzing large datasets.
- Matplotlib: A comprehensive plotting and visualization library for creating static, animated, and interactive visualizations.
This Lesson Will Cover
- 📊 NumPy: What it is and how to use it
- 🏛️ Pandas: Working with structured data
- 📈 Matplotlib: Creating visualizations
- 💡 Common use cases for each library
- 🛠️ Key functions and code examples
Common Use Cases
If these are new to you, then scan through this list of use cases to get an idea of what they are used for:
-
NumPy
- Matrix operations and linear algebra
- Statistical calculations
- Image processing
- Scientific computing
- Machine learning algorithms
-
Pandas
- Data cleaning and preprocessing
- Time series analysis
- Financial data analysis
- CSV/Excel file handling
- Database operations
-
Matplotlib
- Line plots and scatter plots
- Bar charts and histograms
- Heatmaps and contour plots
- Statistical visualizations
- Custom data dashboards
NumPy
NumPy (Numerical Python) provides a powerful alternative to Python’s built-in lists, enabling high-performance operations on multi-dimensional arrays.
Key Features of NumPy
- Efficient in-memory storage with homogeneous element types, plus compiled numerical operations for large datasets. This concerns array layout in RAM; disk storage is a separate consideration.
- Built-in functions for mathematical operations.
- Foundation for libraries like Pandas and TensorFlow.
Getting Started with NumPy
import numpy as np
# Create an array
data = np.array([1, 2, 3, 4, 5])
# Perform operations
print(data * 2) # Element-wise multiplication
# Output: [2 4 6 8 10]
print(np.mean(data)) # Calculate the mean
# Output:
# [ 2 4 6 8 10]
# 3.0
Multi-dimensional Arrays
# Create a 2D array
matrix = np.array([[1, 2], [3, 4]])
# Access elements
print(matrix[0, 1]) # Element in the first row, second column
# Output:
# 2
Random Data Generation
NumPy makes it easy to generate synthetic data:
# Random numbers between 0 and 1
np.random.seed(137)
random_data = np.random.rand(3, 3)
print(random_data)
# Output:
# [[0.94385021 0.08854403 0.69537097]
# [0.69999035 0.49960034 0.50270302]
# [0.89180317 0.08895364 0.84749637]]
Pandas
Pandas provides a high-level data structure called a DataFrame, which allows us to work with structured data in a tabular format—similar to a spreadsheet or SQL table.
Key Features of Pandas
- Read and write data from various formats (CSV, Excel, JSON, etc…)
- Clean and transform data efficiently.
- Seamless integration with other libraries (like scikit-learn).
Loading Data
import pandas as pd
# Load data from a CSV
df = pd.read_csv("data.csv")
# Example data.csv content:
# Name,Age,City,Occupation
# John,25,London,Engineer
# Mary,30,New York,Designer
# Steve,35,Paris,Developer
# Sarah,28,Tokyo,Analyst
# Mike,33,Berlin,Manager
# Preview the data
print(df.head())
# Output:
# Name Age City Occupation
# 0 John 25 London Engineer
# 1 Mary 30 New York Designer
# 2 Steve 35 Paris Developer
# 3 Sarah 28 Tokyo Analyst
# 4 Mike 33 Berlin Manager
# Load from Excel file
df = pd.read_excel("data.xlsx", sheet_name="Sheet1")
# Load from JSON file
df = pd.read_json("data.json")
# Load from SQL database
from sqlalchemy import create_engine
engine = create_engine("sqlite:///database.db")
df = pd.read_sql("SELECT * FROM table_name", engine)
# Load from dictionary
data_dict = {
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 35],
"City": ["Paris", "London", "Tokyo"]
}
df = pd.DataFrame(data_dict)
print(df.dtypes)
# Output:
# Name object
# Age int64
# City object
# dtype: object
DataFrames and Series
- DataFrame: A table of rows and columns with an index.
- Series: A single column, with a name and an index.
data = {"Name": ["Alice", "Bob", "Charlie"], "Age": [25, 30, 35]}
df = pd.DataFrame(data)
# Access a column
print(df["Age"])
# Output:
# 0 25
# 1 30
# 2 35
# Name: Age, dtype: int64
print(df.shape)
# Output: (3, 2)
print(len(df))
# Output: 3
Viewing Data
print(df.shape) # Dimensions (rows, columns)
print(len(df)) # Number of rows
print(df.head()) # First 5 rows
print(df.tail(3)) # Last 3 rows
print(df.info()) # Data info including types
print(df.describe()) # Statistical summary
print(df.columns) # Column names
Selecting Data
print(df["Name"]) # Select single column
print(df[["Name", "Age"]]) # Select multiple columns
print(df.iloc[0]) # Select row by position
print(df.iloc[0:2, 0:2]) # Select range of data by position (rows, cols)
Filtering Data
df = df[df["Age"] > 25] # Apply simple filter
df = df[(df["Age"] > 25) & (df["City"] == "London")] # Apply multiple conditions
df = df[df["Age"].notnull()] # Filter out nulls
Adding/Removing Data
df["Score"] = [95, 85] # Add new column
df = df.drop("Score", axis=1) # Remove column
df = df.drop([0, 1], axis=0) # Remove rows
df = df.dropna() # Remove rows with missing values
df = df.fillna(0) # Fill missing values
Data Types
print(df.dtypes) # Show data types
df["Age"] = df["Age"].astype(float) # Convert type
df["Date"] = pd.to_datetime(df["Date"]) # Convert to datetime
Working with Dates
df["Year"] = df["Date"].dt.year # Extract year
df["Month"] = df["Date"].dt.month # Extract month
df["Weekday"] = df["Date"].dt.day_name() # Get day name
Calculations
print(df["Age"].mean()) # Mean of column
print(df["Age"].median()) # Median
print(df["Age"].max()) # Maximum
print(df.groupby("City")["Age"].mean()) # Group by and calculate
Sorting
df.sort_values("Age", ascending=True) # Sort by one column
df.sort_values(["Age", "Name"], ascending=[True, False]) # Multiple columns
Missing Data
print(df.isnull().sum()) # Count missing values
df.fillna(method="ffill") # Forward fill
df.fillna(method="bfill") # Backward fill
df.interpolate() # Interpolate missing values
String Operations
df["Name"] = df["Name"].str.upper() # Convert to uppercase
df["Name"] = df["Name"].str.strip() # Remove whitespace
df["Name"].str.contains("John") # Check if contains
Merging Data
merged_df = pd.merge(df1, df2, on="id", how="left") # Join dataframes
concat_df = pd.concat([df1, df2], ignore_index=True) # Concatenate dataframes
Writing Data
df.to_csv("output.csv") # Write to CSV
df.to_excel("output.xlsx") # Write to Excel
df.to_json("output.json") # Write to JSON
df.to_sql("table_name", connection) # Write to SQL database
Matplotlib
Matplotlib is the go-to data visualization library for Python. While it’s not commonly used for dashboard development, it’s frequently used for data analysis.
Pandas also integrates with Matplotlib when you call visualization methods on DataFrame objects.
Key Features of Matplotlib
- Create lightweight data visualizations quickly.
- Customize styles, labels, and legends for professional-looking charts.
Here are some examples to give you a flavor of the syntax. Calling plt.show() will render the chart in your Jupyter Notebook or pop open a GUI window on your machine.
Getting Started with Matplotlib
import matplotlib.pyplot as plt
# Basic line plot
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Basic Plot")
plt.show()
Scatter Plots and Histograms
# Scatter plot
plt.scatter(x, y)
plt.title("Scatter Plot")
plt.show()
# Histogram
data = [1, 2, 2, 3, 3, 3, 4, 4, 5]
plt.hist(data, bins=5)
plt.title("Histogram")
plt.show()
Combining with Pandas
df.plot(x="Age", y="Score", kind="bar")
plt.title("Age vs Score")
plt.show()
Conclusion
I learned these tools nearly 10 years ago, and they are still just as relevant today!
It’s amazing to see how much development there’s been in open-source programming languages and Python specifically.
There has never been a better time to use these tools.
Key Takeaways
🏗️ NumPy provides efficient array manipulation and mathematical operations.
📊 Pandas is essential for working with structured data.
📉 Matplotlib allows for quick and flexible data visualization.
🤖 These libraries form the backbone of data analysis and machine learning in Python.
Next: Web Requests and APIs
Up next, we’ll learn all about Python and HTTP—from making requests to hosting your own HTTP server.
Comments (0)
No comments yet.