←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

Introduction to NumPy, Pandas & Matplotlib (Drawing Plots)

Study material and explanations for Unit 5

Introduction to NumPy, Pandas & Matplotlib (Drawing Plots)

Python is the #1 programming language in the world for Data Science, Analytics, and Machine Learning because of three foundational libraries: NumPy, Pandas, and Matplotlib.

The Golden Trio of Python Data Science Libraries
1. NumPy (Numerical Python)
Fast multi-dimensional arrays (ndarray), matrices, and linear algebra calculations.
2. Pandas (Panel Data)
Tabular data manipulation using Series (1D) and DataFrame (2D Excel-like tables).
3. Matplotlib
Data visualization library for drawing 2D graphs (Line, Bar, Scatter, Histogram, Pie charts).

1. Introduction to NumPy (Numerical Python)

NumPy (import numpy as np) is the core library for scientific and numerical computing in Python. Its main object is the homogeneous multidimensional array called ndarray (N-dimensional array).

Why Use NumPy Arrays Instead of Python Lists?

Feature Python list NumPy ndarray
Data Types Heterogeneous (can mix types) Homogeneous (all elements must be of the same type)
Speed Slower for math operations Up to 50x Faster (written in optimized C)
Memory Usage Consumes more memory Compact and consumes much less memory
Element-wise Math [1, 2] * 2 repeats list [1, 2, 1, 2] arr * 2 multiplies every element [2, 4] (Vectorization)

Creating & Using NumPy Arrays:

import numpy as np

# 1. Creating a 1D NumPy Array
arr1 = np.array([10, 20, 30, 40])
print("1D Array:", arr1)
print("Add 5 to each element:", arr1 + 5)  # Output: [15 25 35 45]

# 2. Creating a 2D Matrix (Rows x Columns)
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print("Shape (rows, cols):", matrix.shape) # Output: (2, 3)
print("Dimensions (ndim):", matrix.ndim)   # Output: 2

# 3. Built-in Array Generators & Statistical Functions
zeros_arr = np.zeros((2, 2))               # 2x2 array of 0.0
range_arr = np.arange(1, 10, 2)            # [1, 3, 5, 7, 9]
print("Mean:", np.mean(arr1), "Max:", np.max(arr1), "Sum:", np.sum(arr1))

2. Introduction to Pandas (Data Analysis Library)

Pandas (import pandas as pd) is built on top of NumPy and is used for cleaning, analyzing, and manipulating structured tabular data (like CSV files, Excel spreadsheets, and SQL tables).

The Two Core Data Structures of Pandas:

  1. Series (1-Dimensional): A single labeled column of data (like a 1D array with custom index labels).
  2. DataFrame (2-Dimensional): A 2D table consisting of Rows and Columns (just like an Excel sheet or SQL table).
import pandas as pd

# Creating a 2D DataFrame from a Python Dictionary
data = {
    "Roll_No": [101, 102, 103, 104],
    "Name": ["Aarav", "Diya", "Karan", "Sneha"],
    "Marks": [85, 92, 76, 89]
}

df = pd.DataFrame(data)
print("--- Full Student Table ---")
print(df)

# Useful Pandas Inspection & Filtering Operations:
print("\nFirst 2 rows:\n", df.head(2))               # Top 2 rows
print("\nAverage Marks:", df["Marks"].mean())        # Mean of Marks column
print("\nToppers (>85):\n", df[df["Marks"] > 85])    # Filter rows where Marks > 85

# Reading & Writing CSV files in 1 line:
# df = pd.read_csv("students.csv")
# df.to_csv("output.csv", index=False)

3. Introduction to Matplotlib & Drawing Plots

Matplotlib is Python’s most popular 2D Data Visualization library. Its primary sub-module is matplotlib.pyplot (imported as plt), which allows us to draw publication-quality graphs and charts in just a few lines of code.

import matplotlib.pyplot as plt

Common Plotting Functions in matplotlib.pyplot:

Function Chart Type Drawn When to Use It
plt.plot(x, y) Line Graph Showing trends over time (e.g., yearly sales or temperature)
plt.bar(x, y) Bar Chart Comparing quantities across categories (e.g., marks per subject)
plt.scatter(x, y) Scatter Plot Showing relationship/correlation between two variables
plt.pie(sizes) Pie Chart Showing percentage share of a whole (e.g., market share)
plt.hist(data) Histogram Showing frequency distribution of continuous numeric data

Example 1: Drawing a Line Plot (plt.plot())

import matplotlib.pyplot as plt

# Data coordinates (X-axis and Y-axis)
semesters = [1, 2, 3, 4, 5]
sgpa = [7.8, 8.1, 8.5, 8.4, 9.1]

# Draw Line Graph
plt.plot(semesters, sgpa, color="blue", marker="o", linestyle="--")

# Add Title and Axis Labels
plt.title("BCA Student SGPA Progress")
plt.xlabel("Semester")
plt.ylabel("SGPA Scored")
plt.grid(True)

# Display the Plot Window
plt.show()

Example 2: Drawing a Bar Chart (plt.bar()) & Pie Chart (plt.pie())

import matplotlib.pyplot as plt

subjects = ["Python", "Java", "OS", "CyberSec"]
marks = [92, 85, 78, 88]

# 1. Drawing a Bar Chart
plt.bar(subjects, marks, color=["#3b82f6", "#10b981", "#f59e0b", "#ec4899"])
plt.title("Subject-wise Marks in BCA")
plt.xlabel("Subjects")
plt.ylabel("Marks Obtained")
plt.show()

# 2. Drawing a Pie Chart
plt.pie(marks, labels=subjects, autopct="%1.1f%%", startangle=90)
plt.title("Marks Distribution")
plt.show()