NumPy Tutorial for Class 11
Introduction
When you start working with numbers in Python, especially large amounts of data, you will notice that Python lists are not always fast or convenient. To solve this problem, Python provides a powerful library called NumPy. It makes numerical work easier, faster, and more efficient.
What is NumPy?
NumPy stands for Numerical Python.
It is a Python library used to work with numerical data and arrays. It is commonly used in data science, machine learning, and scientific computing.
Founder and Year
NumPy was created by Travis Oliphant in 2005.
He built it by improving older Python numerical libraries to make mathematical work easier in Python.
Why Do We Use NumPy?
NumPy is preferred over Python lists because:
- It is faster.
- It uses less memory.
- It supports easy mathematical operations.
- It allows multi-dimensional data (like matrices).
For example, if you want to add 10 to every element in a list, Python lists require a loop, but NumPy can do it in a single line.
Installing NumPy
To install NumPy, use the following command:
pip install numpy
Creating NumPy Arrays
Creating arrays is the most basic and important step in NumPy.
Step 1: Import NumPy
import numpy as np
Step 2: Create a Python List
my_list = [10, 20, 30, 40]
Step 3: Convert the List to a NumPy Array
arr = np.array(my_list)
print(arr)
Output:
[10 20 30 40]
1D Array Example
import numpy as np
numbers = [5, 10, 15, 20]
arr = np.array(numbers)
print(arr)
2D Array Example
import numpy as np
list2d = [
[1, 2, 3],
[4, 5, 6]
]
arr2d = np.array(list2d)
print(arr2d)
Output:
[[1 2 3]
[4 5 6]]
Setting Data Type (dtype)
You can specify the data type of array elements:
arr = np.array([1, 2, 3], dtype=float)
print(arr)
Output:
[1. 2. 3.]
Array Properties
These properties help you understand the structure of an array.
arr.shape # Shows rows and columns
arr.size # Total number of elements
arr.ndim # Number of dimensions (1D or 2D)
arr.dtype # Data type of elements
Example:
arr = np.array([[1, 2], [3, 4]])
print(arr.shape) # (2, 2)
print(arr.size) # 4
print(arr.ndim) # 2
print(arr.dtype) # int64 or int32
Basic Mathematical Operations
NumPy allows direct mathematical operations on arrays.
arr + 5
arr * 2
Example of adding two arrays:
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
print(x + y) # [5 7 9]
print(x * y) # [4 10 18]
Convert NumPy Array Back to List
arr.tolist()
Practice Questions
- Convert the list
[2, 4, 6]into a NumPy array and add 10. - Create a 2D array using
[[1, 2], [3, 4]]and print its shape. - Create an array with float values from
[1, 2, 3]. - Convert any NumPy array back to a Python list.
Summary
- NumPy stands for Numerical Python.
- It was created by Travis Oliphant in 2005.
- It is faster and more powerful than Python lists.
- Arrays are created using
np.array(). - Important properties:
shape,size,ndim,dtype. - NumPy supports easy mathematical operations.
