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 |
|---|---|
ndim | Number of dimensions |
shape | Dimensions of the array |
size | Total number of elements |
dtype | Data type of elements |
T | Transpose 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.
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
No comments:
Post a Comment