Total Pageviews

Thursday, August 13, 2026

Pandas for data science

 

  • Handles missing data (NaN, NA, NaT easily).
  • Flexible size mutability (insert/delete columns).
  • Automatic data alignment (aligns labels automatically).
  • Powerful groupby engine (split-apply-combine operations).
  • Easy data conversion (converts structures to DataFrames).
  • Smart indexing (label-based slicing and subsetting).
  • Intuitive data merging (easy joining of datasets).
  • Flexible reshaping (pivoting and restructuring data).
  • Hierarchical axis labeling (multiple labels per tick).
  • Robust I/O tools (loads CSV, Excel, HDF5).
  • Time-series ready (date shifting and frequency conversion).

  • Series: One-dimensional array-like structure.
  • DataFrame: Two-dimensional, size-mutable tabular structure.

1.
import pandas as pd
s = pd.Series([1, 3, 5, 7, 9])
print(s)


0    1
1    3
2    5
3    7
4    9
dtype: int64




2.

data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],
        'Age': [28, 34, 29, 32]}
df = pd.DataFrame(data)
print(df)


    Name  Age
0   John   28
1   Anna   34
2  Peter   29
3  Linda   32



3.

# Creating a DataFrame from a dictionary. import pandas as pd data = { 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['New York', 'Paris', 'London'] } df = pd.DataFrame(data) print(df)



4. # To look at the first few rows of a DataFrame. print(df.head()) # First five rows

      Name  Age      City
0    Alice   25  New York
1      Bob   30     Paris
2  Charlie   35    London



5.
# To access a column in the DataFrame.
ages = df['Age']
print(ages)
print(df['Name']) # Displays the 'Name' column

0    25
1    30
2    35
Name: Age, dtype: int64
0      Alice
1        Bob
2    Charlie
Name: Name, dtype: object


6.

subset = df[0:2] # First two rows print(subset)


    Name  Age      City
0  Alice   25  New York
1    Bob   30     Paris


7.


filtered_df = df[df['Age'] > 30] # Rows where age is greater than 30 print(filtered_df)

      Name  Age    City
2  Charlie   35  London



8.

df['AgeInTenYears'] = df['Age'] + 10 print(df)

      Name  Age      City  AgeInTenYears
0    Alice   25  New York             35
1      Bob   30     Paris             40
2  Charlie   35    London             45



9.
print(df.describe())

        Age  AgeInTenYears
count   3.0            3.0
mean   30.0           40.0
std     5.0            5.0
min    25.0           35.0
25%    27.5           37.5
50%    30.0           40.0
75%    32.5           42.5
max    35.0           45.0


10.
f.rename(columns={'AgeYears': 'Age'}, inplace=True) #print(df['Age'].mean()) # Average age


11.
df print(df['Age'].mean()) # Average age

30.0


12.
df.plot(kind='line')





df['Age'].plot(kind='bar')



# Select rows where 'Age' is greater than 30 print(df[df['Age'] > 30]) filtered_df = df[df['Age'] > 30] # Rows where age is greater than 30 print(filtered_df)

     Name   Age    City  AgeInTenYears
2  Charlie  35.0  London             45
      Name   Age    City  AgeInTenYears
2  Charlie  35.0  London             45















#DATA CLEANING #Drop Rows With Missing Values import pandas as pd # Define a dictionary with Indian employee data containing missing values (None) data = { "Employee": ["Aarav", "Priya", "Rahul", "Ananya", "Kabir"], "Salary_LPA": [12.0, None, 18.5, 9.0, 15.0], # Priya's salary is missing "City": ["Mumbai", "Delhi", None, "Bangalore", None], # Rahul and Kabir have missing cities } df = pd.DataFrame(data) print("Original Data:\n", df) print() # Use dropna() to remove rows that contain any missing values df_cleaned = df.dropna() print("Cleaned Data (Rows with any missing values removed):\n", df_cleaned)


Original Data:
   Employee  Salary_LPA       City
0    Aarav        12.0     Mumbai
1    Priya         NaN      Delhi
2    Rahul        18.5       None
3   Ananya         9.0  Bangalore
4    Kabir        15.0       None

Cleaned Data (Rows with any missing values removed):
   Employee  Salary_LPA       City
0    Aarav        12.0     Mumbai
3   Ananya         9.0  Bangalore




#Fill Missing Values import pandas as pd # define a dictionary with sample data which includes some missing values data = { 'A': [1, 2, 3, None, 5], 'B': [None, 2, 3, 4, 5], 'C': [1, 2, None, None, 5] } df = pd.DataFrame(data) print("Original Data:\n", df) # filling NaN values with 0 df.fillna(0, inplace=True) print("\nData after filling NaN with 0:\n", df)



Original Data:
      A    B    C
0  1.0  NaN  1.0
1  2.0  2.0  2.0
2  3.0  3.0  NaN
3  NaN  4.0  NaN
4  5.0  5.0  5.0

Data after filling NaN with 0:
      A    B    C
0  1.0  0.0  1.0
1  2.0  2.0  2.0
2  3.0  3.0  0.0
3  0.0  4.0  0.0
4  5.0  5.0  5.0




import pandas as pd # define a dictionary with sample data which includes some missing values data = { 'A': [1, 2, 3, None, 5], 'B': [None, 2, 3, 4, 5], 'C': [1, 2, None, None, 5] } df = pd.DataFrame(data) print("Original Data:\n", df) # filling NaN values with the mean of each column df.fillna(df.mean(), inplace=True) print("\nData after filling NaN with mean:\n", df)



Original Data:
      A    B    C
0  1.0  NaN  1.0
1  2.0  2.0  2.0
2  3.0  3.0  NaN
3  NaN  4.0  NaN
4  5.0  5.0  5.0

Data after filling NaN with mean:
       A    B         C
0  1.00  3.5  1.000000
1  2.00  2.0  2.000000
2  3.00  3.0  2.666667
3  2.75  4.0  2.666667
4  5.00  5.0  5.000000



import pandas as pd # sample data data = { 'A': [1, 2, 2, 3, 3, 4], 'B': [5, 6, 6, 7, 8, 8] } df = pd.DataFrame(data) print("Original DataFrame:\n", df.to_string(index=False)) # detect duplicates print("\nDuplicate Rows:\n", df[df.duplicated()].to_string(index=False)) # remove duplicates based on column 'A' df.drop_duplicates(subset=['A'], keep='first', inplace=True) print("\nDataFrame after removing duplicates based on column 'A':\n", df.to_string(index=False))

Original DataFrame: A B 1 5 2 6 2 6 3 7 3 8 4 8 Duplicate Rows: A B 2 6 DataFrame after removing duplicates based on column 'A': A B 1 5 2 6 3 7 4 8















matplotlib

Matplotlib for Data Science

A Practical Python Tutorial with Examples and Output

Introduction to Matplotlib

Matplotlib is a Python library used to create visualizations such as line charts, bar charts, scatter plots, histograms, pie charts and many other types of graphs.

It is widely used in Data Science, Machine Learning, Scientific Computing, Statistics and data analysis. The matplotlib.pyplot interface provides convenient plotting functions, while Matplotlib also supports an object-oriented approach using Figure and Axes objects.

Student Tip: Learn Matplotlib after NumPy because NumPy arrays are commonly used as the numerical input for plotting.

1. Installing Matplotlib

Matplotlib can be installed using pip.

pip install matplotlib

After installation, import the pyplot module.

import matplotlib.pyplot as plt

Output

Matplotlib imported successfully.

2. Creating a Simple Line Plot

The plot() function is one of the most commonly used Matplotlib functions.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]

plt.plot(x, y)
plt.show()

Output

A line graph is displayed with the values of x on the horizontal axis and y on the vertical axis.


3. Adding a Title

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]

plt.plot(x, y)
plt.title("Student Performance")
plt.show()

Output

Student Performance

The graph appears with Student Performance as its title.


4. Adding X-Axis and Y-Axis Labels

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]

plt.plot(x, y)

plt.title("Student Performance")
plt.xlabel("Study Hours")
plt.ylabel("Marks")

plt.show()

Output

The graph contains:

  • Title: Student Performance
  • X-axis: Study Hours
  • Y-axis: Marks

5. Adding Markers

Markers can be used to show individual data points.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [20, 35, 30, 50, 45]

plt.plot(x, y, marker='o')

plt.title("Marks")
plt.xlabel("Student")
plt.ylabel("Marks")

plt.show()

Output

A line graph is displayed with circular markers at every data point.


6. Changing Line Style

Matplotlib allows different line styles such as solid, dashed and dotted lines.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 25, 20, 40, 35]

plt.plot(x, y, linestyle='--')

plt.title("Dashed Line")
plt.show()

Output

A dashed line graph is displayed.

7. Multiple Lines in One Graph

import matplotlib.pyplot as plt

months = [1, 2, 3, 4, 5]

sales = [100, 120, 150, 170, 200]
profit = [20, 30, 35, 45, 55]

plt.plot(months, sales)
plt.plot(months, profit)

plt.title("Sales and Profit")
plt.xlabel("Month")
plt.ylabel("Amount")

plt.show()

Output

Two lines are displayed on the same graph representing Sales and Profit.


8. Adding a Legend

import matplotlib.pyplot as plt

months = [1, 2, 3, 4, 5]

sales = [100, 120, 150, 170, 200]
profit = [20, 30, 35, 45, 55]

plt.plot(months, sales, label="Sales")
plt.plot(months, profit, label="Profit")

plt.title("Sales and Profit")
plt.xlabel("Month")
plt.ylabel("Amount")

plt.legend()

plt.show()

Output

The graph displays a legend identifying the two lines as Sales and Profit.


9. Adding Grid Lines

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]

plt.plot(x, y, marker='o')
plt.grid()

plt.title("Line Graph with Grid")
plt.show()

Output

Grid lines are displayed behind the graph to make the values easier to read.


10. Creating a Bar Chart

The bar() function is useful for comparing categorical values.

import matplotlib.pyplot as plt

subjects = ["C", "Python", "Java", "DBMS"]
marks = [75, 85, 80, 70]

plt.bar(subjects, marks)

plt.title("Subject-wise Marks")
plt.xlabel("Subjects")
plt.ylabel("Marks")

plt.show()

Output

A bar chart displays the marks obtained in C, Python, Java and DBMS.


11. Horizontal Bar Chart

import matplotlib.pyplot as plt

subjects = ["C", "Python", "Java", "DBMS"]
marks = [75, 85, 80, 70]

plt.barh(subjects, marks)

plt.title("Subject-wise Marks")
plt.xlabel("Marks")
plt.ylabel("Subjects")

plt.show()

Output

A horizontal bar chart is displayed.


12. Creating a Scatter Plot

A scatter plot displays individual observations as points and is useful for studying relationships between two numerical variables.

import matplotlib.pyplot as plt

study = [1, 2, 3, 4, 5, 6]
marks = [40, 45, 55, 65, 75, 85]

plt.scatter(study, marks)

plt.title("Study Hours vs Marks")
plt.xlabel("Study Hours")
plt.ylabel("Marks")

plt.show()

Output

A scatter plot is displayed showing the relationship between study hours and marks.


13. Creating a Histogram

A histogram shows the distribution of numerical data by grouping values into bins.

import matplotlib.pyplot as plt

marks = [45, 50, 52, 55, 60, 62, 65, 68,
         70, 72, 75, 78, 80, 85, 90]

plt.hist(marks, bins=5)

plt.title("Distribution of Marks")
plt.xlabel("Marks")
plt.ylabel("Frequency")

plt.show()

Output

A histogram displays how frequently marks occur within different ranges.


14. Creating a Pie Chart

import matplotlib.pyplot as plt

subjects = ["C", "Python", "Java", "DBMS"]
marks = [75, 85, 80, 70]

plt.pie(marks, labels=subjects, autopct='%1.1f%%')

plt.title("Subject-wise Marks Distribution")

plt.show()

Output

A pie chart is displayed showing the percentage contribution of each subject.


15. Exploding a Pie Chart Slice

import matplotlib.pyplot as plt

subjects = ["C", "Python", "Java", "DBMS"]
marks = [75, 85, 80, 70]

explode = [0, 0.1, 0, 0]

plt.pie(
    marks,
    labels=subjects,
    explode=explode,
    autopct='%1.1f%%'
)

plt.title("Subject-wise Marks")

plt.show()

Output

The Python portion is separated slightly from the center of the pie chart.


16. Creating Subplots

Subplots allow multiple graphs to be displayed within the same figure.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]

plt.subplot(1, 2, 1)
plt.plot(x, y)
plt.title("Line Plot")

plt.subplot(1, 2, 2)
plt.bar(x, y)
plt.title("Bar Plot")

plt.show()

Output

Two plots are displayed side by side:

  • Line plot
  • Bar plot

17. Using Figure and Axes

For more structured and reusable visualizations, Matplotlib supports the object-oriented approach using a Figure and one or more Axes.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [10, 20, 15, 30]

fig, ax = plt.subplots()

ax.plot(x, y)
ax.set_title("Simple Plot")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values")

plt.show()

Output

A line plot is displayed with a title and axis labels.


18. Changing Figure Size

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]

plt.figure(figsize=(8, 5))

plt.plot(x, y)
plt.title("Large Figure")

plt.show()

Output

The graph is displayed using a figure size of 8 × 5 inches.


19. Saving a Graph

A Matplotlib figure can be saved to an image file using savefig().

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]

plt.plot(x, y)
plt.title("My Graph")

plt.savefig("my_graph.png")

plt.show()

Output

my_graph.png

The graph is saved as my_graph.png.


20. Practical Example — Student Performance

The following example combines several Matplotlib features to visualize student performance.

import matplotlib.pyplot as plt

students = ["A", "B", "C", "D", "E"]

marks = [65, 72, 88, 55, 92]

plt.bar(students, marks)

plt.title("Student Performance")
plt.xlabel("Students")
plt.ylabel("Marks")

plt.ylim(0, 100)
plt.grid(axis='y')

plt.show()

Output

A bar chart is displayed showing the marks of five students. The Y-axis ranges from 0 to 100.


21. Practical Example — Sales Analysis

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]

sales = [120, 150, 135, 180, 210, 240]

plt.plot(
    months,
    sales,
    marker='o'
)

plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")

plt.grid()
plt.show()

Output

A line chart displays the monthly sales trend from January to June.


22. Practical Example — Study Hours and Marks

import matplotlib.pyplot as plt

study_hours = [1, 2, 3, 4, 5, 6, 7]
marks = [35, 42, 50, 61, 70, 82, 90]

plt.scatter(study_hours, marks)

plt.title("Study Hours vs Marks")
plt.xlabel("Study Hours")
plt.ylabel("Marks")

plt.grid()
plt.show()

Output

A scatter plot shows the relationship between study hours and marks.


23. Important Matplotlib Plotting Functions

Function Purpose
plt.plot() Line plot
plt.bar() Vertical bar chart
plt.barh() Horizontal bar chart
plt.scatter() Scatter plot
plt.hist() Histogram
plt.pie() Pie chart
plt.subplot() Create subplot
plt.show() Display figure
plt.savefig() Save figure

24. Important Matplotlib Commands

Command Purpose
plt.title() Set graph title
plt.xlabel() Label X-axis
plt.ylabel() Label Y-axis
plt.legend() Display legend
plt.grid() Display grid
plt.xlim() Set X-axis limits
plt.ylim() Set Y-axis limits
plt.figure() Create/configure a figure
plt.show() Display the graph

25. Matplotlib with NumPy

NumPy and Matplotlib are frequently used together for numerical data analysis and visualization.

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 10, 0.5)

y = x ** 2

plt.plot(x, y)

plt.title("y = x²")
plt.xlabel("x")
plt.ylabel("y")

plt.grid()
plt.show()

Output

A smooth line graph representing the mathematical function y = x² is displayed.


26. Matplotlib in Data Science

Matplotlib is useful when data scientists need to understand data visually. Graphs can reveal trends, relationships, distributions and unusual observations that may not be obvious from raw numerical values.

  • Line Plot: Useful for trends over time.
  • Bar Chart: Useful for comparing categories.
  • Scatter Plot: Useful for relationships between numerical variables.
  • Histogram: Useful for understanding distributions.
  • Pie Chart: Useful for showing proportions.

27. Figure and Axes — Basic Concept

Figure: The complete visualization window or canvas.

Axes: The area inside a figure where data is actually plotted.

Axis: The numerical or categorical scale shown along the X-axis or Y-axis.

A figure can contain one or more Axes. This is particularly useful when creating dashboards or multiple related visualizations.


28. Complete Example

import numpy as np
import matplotlib.pyplot as plt

students = np.array([
    "A", "B", "C", "D", "E"
])

marks = np.array([
    65, 72, 88, 55, 92
])

fig, ax = plt.subplots(figsize=(8, 5))

ax.bar(students, marks)

ax.set_title("Student Performance")
ax.set_xlabel("Students")
ax.set_ylabel("Marks")

ax.set_ylim(0, 100)

ax.grid(axis='y')

plt.show()

Output

A professional student-performance bar chart is displayed with:

  • Student names on the X-axis
  • Marks on the Y-axis
  • Title
  • Grid lines
  • Y-axis range from 0 to 100

Summary

In this tutorial, we learned the fundamentals of Matplotlib and how it can be used to visualize numerical and categorical data.

  • Installing Matplotlib
  • Importing matplotlib.pyplot
  • Creating line plots
  • Adding titles and labels
  • Using markers and line styles
  • Creating multiple lines
  • Adding legends and grids
  • Creating bar charts
  • Creating horizontal bar charts
  • Creating scatter plots
  • Creating histograms
  • Creating pie charts
  • Creating subplots
  • Using Figure and Axes
  • Changing figure size
  • Saving graphs
  • Using Matplotlib with NumPy
  • Visualizing student and sales data

Created by Bijan Krishna Paul

Computer Science • Python • Data Science

SciPy

 SciPy

NumPy

NumPy for Data Science

A Practical Python Tutorial with Examples and Output

Introduction to NumPy

NumPy (Numerical Python) is one of the most important Python libraries for numerical and scientific computing. It provides a powerful multidimensional array object called ndarray and many functions for mathematical, statistical, logical and array-based operations.

NumPy is widely used in Data Science, Machine Learning, Artificial Intelligence, Scientific Computing, Image Processing and numerical analysis.

Why Use NumPy?

  • Fast numerical calculations
  • Multidimensional arrays
  • Efficient mathematical operations
  • Array indexing and slicing
  • Statistical functions such as mean, median and standard deviation
  • Random number generation
  • Matrix and linear algebra operations
  • Useful foundation for Pandas, SciPy, scikit-learn and many scientific Python tools

1. Installing NumPy

NumPy can normally be installed using pip.

pip install numpy

After installation, import NumPy using the alias np.

import numpy as np
print(np.__version__)

Output

2.5.0

Note: The exact version displayed depends on the NumPy version installed on your computer.


2. Creating a NumPy Array

The basic NumPy data structure is the ndarray, a multidimensional array whose elements have a common data type.

import numpy as np

arr = np.array([10, 20, 30, 40, 50])

print(arr)

Output

[10 20 30 40 50]

3. Creating a Two-Dimensional Array

A two-dimensional NumPy array can be created using nested lists.

import numpy as np

arr = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

print(arr)

Output

[[1 2 3]
 [4 5 6]]

4. Checking Dimensions

The ndim attribute tells us the number of dimensions of an array.

import numpy as np

a = np.array([1, 2, 3])

b = np.array([
    [1, 2],
    [3, 4]
])

print("Dimensions of a:", a.ndim)
print("Dimensions of b:", b.ndim)

Output

Dimensions of a: 1
Dimensions of b: 2

5. Shape of an Array

The shape attribute gives the size of the array along each dimension.

import numpy as np

arr = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

print(arr.shape)

Output

(2, 3)

Here, 2 represents rows and 3 represents columns.


6. Size of an Array

The size attribute returns the total number of elements.

import numpy as np

arr = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

print(arr.size)

Output

6

7. Data Type of an Array

The dtype attribute tells us the data type of array elements.

import numpy as np

arr = np.array([10, 20, 30])

print(arr.dtype)

Output

int64

The exact integer dtype can vary depending on the platform.


8. Array Indexing

Array elements can be accessed using their index. Python uses zero-based indexing.

import numpy as np

arr = np.array([10, 20, 30, 40, 50])

print(arr[0])
print(arr[2])
print(arr[-1])

Output

10
30
50

9. Array Slicing

Slicing allows us to select a portion of an array.

import numpy as np

arr = np.array([10, 20, 30, 40, 50])

print(arr[1:4])
print(arr[:3])
print(arr[2:])

Output

[20 30 40]
[10 20 30]
[30 40 50]

10. Creating Arrays with arange()

np.arange() creates values within a specified range.

import numpy as np

arr = np.arange(1, 11)

print(arr)

Output

[ 1  2  3  4  5  6  7  8  9 10]

11. Creating an Array of Zeros

import numpy as np

arr = np.zeros(5)

print(arr)

Output

[0. 0. 0. 0. 0.]

12. Creating an Array of Ones

import numpy as np

arr = np.ones(5)

print(arr)

Output

[1. 1. 1. 1. 1.]

13. Mathematical Operations on Arrays

NumPy supports element-wise arithmetic operations on arrays.

import numpy as np

a = np.array([10, 20, 30])
b = np.array([1, 2, 3])

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)

Output

Addition: [11 22 33]
Subtraction: [ 9 18 27]
Multiplication: [10 40 90]
Division: [10. 10. 10.]

14. Sum of Array Elements

import numpy as np

arr = np.array([10, 20, 30, 40, 50])

print("Sum =", np.sum(arr))

Output

Sum = 150

15. Mean, Median and Standard Deviation

import numpy as np

marks = np.array([60, 70, 80, 90, 100])

print("Mean =", np.mean(marks))
print("Median =", np.median(marks))
print("Standard Deviation =", np.std(marks))

Output

Mean = 80.0
Median = 80.0
Standard Deviation = 14.142135623730951

16. Minimum and Maximum

import numpy as np

arr = np.array([25, 10, 45, 30, 15])

print("Minimum =", np.min(arr))
print("Maximum =", np.max(arr))

Output

Minimum = 10
Maximum = 45

17. Reshaping an Array

The reshape() operation changes the structure of an array without changing the number of elements.

import numpy as np

arr = np.arange(1, 7)

new_arr = arr.reshape(2, 3)

print(new_arr)

Output

[[1 2 3]
 [4 5 6]]

18. Sorting an Array

import numpy as np

arr = np.array([50, 10, 40, 20, 30])

print(np.sort(arr))

Output

[10 20 30 40 50]

19. Finding Unique Values

import numpy as np

arr = np.array([10, 20, 20, 30, 30, 30, 40])

print(np.unique(arr))

Output

[10 20 30 40]

20. Filtering Array Elements

Boolean conditions can be used to select elements satisfying a particular condition.

import numpy as np

marks = np.array([35, 45, 60, 75, 90])

result = marks[marks >= 50]

print(result)

Output

[60 75 90]

21. Random Numbers

NumPy provides facilities for random simulation and random-number generation.

import numpy as np

np.random.seed(10)

arr = np.random.randint(1, 101, 5)

print(arr)

Output

[10 16 65 29 90]

22. Matrix Multiplication

NumPy supports matrix multiplication and linear-algebra operations.

import numpy as np

A = np.array([
    [1, 2],
    [3, 4]
])

B = np.array([
    [5, 6],
    [7, 8]
])

C = A @ B

print(C)

Output

[[19 22]
 [43 50]]

23. Transpose of a Matrix

import numpy as np

A = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

print(A.T)

Output

[[1 4]
 [2 5]
 [3 6]]

24. Concatenating Arrays

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

result = np.concatenate((a, b))

print(result)

Output

[1 2 3 4 5 6]

25. Practical Example — Student Marks

NumPy can be used to perform quick numerical analysis of student marks.

import numpy as np

marks = np.array([65, 72, 81, 55, 90])

print("Marks:", marks)
print("Average:", np.mean(marks))
print("Highest:", np.max(marks))
print("Lowest:", np.min(marks))
print("Passed:", marks[marks >= 40])

Output

Marks: [65 72 81 55 90]
Average: 72.6
Highest: 90
Lowest: 55
Passed: [65 72 81 55 90]

Important NumPy Attributes

Attribute Purpose
ndimNumber of dimensions
shapeDimensions of the array
sizeTotal number of elements
dtypeData type of elements
TTranspose of an array

Important NumPy Functions

Function Use
np.array()Create an array
np.arange()Generate a range of values
np.zeros()Create an array of zeros
np.ones()Create an array of ones
np.sum()Calculate sum
np.mean()Calculate mean
np.median()Calculate median
np.std()Calculate standard deviation
np.min()Find minimum
np.max()Find maximum
np.sort()Sort array values
np.unique()Find unique values
np.concatenate()Join arrays

NumPy and Data Science

NumPy forms an important numerical foundation for the Python data-science ecosystem. Its multidimensional arrays and numerical routines are useful for data preparation, mathematical calculations, statistics, simulations and machine-learning workflows.

Student Tip: Before learning Pandas and Machine Learning, understand NumPy arrays, indexing, slicing, reshaping, mathematical operations and basic statistics.

Summary

In this tutorial we learned the fundamental concepts of NumPy:

  • Installing and importing NumPy
  • Creating one-dimensional and multidimensional arrays
  • Indexing and slicing
  • Array dimensions, shape, size and data type
  • Creating arrays using zeros, ones and arange
  • Arithmetic operations
  • Statistical operations
  • Sorting and filtering
  • Reshaping arrays
  • Random number generation
  • Matrix operations
  • Transpose and concatenation

Created by Bijan Krishna Paul

Computer Science • Python • Data Science

scikit-learn

 Scikit-Learn provides core machine learning tools. These include model evaluation functions like accuracy_score, data preparation tools like StandardScaler, and model selection helpers like train_test_split. It also features clustering algorithms like KMeans, classification models like SVC, and regression models like LinearRegression.

Evaluation and Preprocessing
  • Measures accuracy and error with accuracy_score and mean_squared_error
  • Builds confusion matrices with confusion_matrix
  • Scales data using StandardScaler and MinMaxScaler
  • Encodes labels with LabelEncoder
  • Fills missing data via SimpleImputer 
Selection and Clustering
  • Splits data using train_test_split
  • Tunes parameters with GridSearchCV
  • Validates models using cross_val_score
  • Groups data with KMeans
  • Uses hierarchical groups via AgglomerativeClustering 
Classification and Regression
  • Predicts classes with KNeighborsClassifier and SVC
  • Uses trees and Bayes via DecisionTreeClassifier and GaussianNB
  • Fits linear equations with LinearRegression and Lasso
  • Predicts values using RandomForestRegressor 

4. image input and display (gray scale)

 


8. Image Thresholding using OpenCV (or Image Binarization).








 

7. Image Thresholding using OpenCV (or Image Binarization).








 

6. OpenCV image reading and writing

 


5. OpenCV image reading and writing

 5. 





3. Get number of pixel, dimension of image

 import cv2


img = cv2.imread('im1.jpg')


cv2.imshow("Cute Kitens", img)

print("Image Properties")

print("- Number of Pixels: " + str(img.size))

print("- Shape/Dimensions: " + str(img.shape))



OUTPUT:

Image Properties
- Number of Pixels: 489402
- Shape/Dimensions: (318, 513, 3)


2. image input and display (color)

 import cv2

img = cv2.imread("im.jpeg", cv2.IMREAD_COLOR)

cv2.imshow("Cute Kitens", img)

cv2.waitKey(0)

cv2.destroyAllWindows()

output:






1. image input and display



CODE :


 import cv2

img = cv2.imread("im.jpeg")

cv2.imshow("Cute Kitens", img)

cv2.waitKey(0)

cv2.destroyAllWindows()