๐ Introduction to NumPy
What is NumPy?
NumPy (Numerical Python) is a powerful Python library used for numerical computations. It provides support for arrays, matrices, and many mathematical functions.
Why use NumPy?
- Faster than Python lists
- Supports multi-dimensional arrays
- Optimized mathematical functions
- Useful for data science, ML, and scientific computing
Installation
pip install numpy
Importing NumPy
import numpy as np
Real-Life Example:
You can analyze thousands of sales records, do calculations, and generate statistics quickly using NumPy arrays.
๐น Creating Arrays
arr1 = np.array([1, 2, 3]) # 1D array
arr2 = np.array([[1, 2], [3, 4]]) # 2D array
Array Attributes
print(arr2.shape) # (2, 2)
print(arr2.ndim) # 2
print(arr2.dtype) # int32 or int64
Real-Life Example:
Use 2D arrays to represent Excel-like tables (e.g., student marks, sales data).
๐น Indexing and Slicing
arr = np.array([10, 20, 30, 40])
print(arr[1:3]) # Output: [20 30]
arr2 = np.array([[1, 2], [3, 4]])
print(arr2[1, 0]) # Output: 3
Real-Life Example:
Get a student’s marks from a 2D array of student results.
๐น Array Operations
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b) # [5 7 9]
print(a * b) # [4 10 18]
Broadcasting
a = np.array([1, 2, 3])
print(a + 10) # [11 12 13]
Real-Life Example:
Apply discount or tax to a list of prices using broadcasting.
๐น Array Functions
arr = np.array([1, 2, 3, 4])
print(np.sum(arr)) # 10
print(np.mean(arr)) # 2.5
print(np.max(arr)) # 4
Real-Life Example:
Calculate total or average marks of students.
๐น Reshaping and Flattening
arr = np.array([[1, 2], [3, 4]])
print(arr.reshape(4, 1))
print(arr.flatten())
Real-Life Example:
Convert a 2D image matrix into a 1D array for machine learning input.
๐น Stacking and Splitting
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(np.vstack((a, b)))
print(np.hstack((a, b)))
๐น Random Numbers
np.random.seed(0)
print(np.random.randint(1, 10, size=(2, 3)))
Real-Life Example:
Create random roll numbers or question orders for an online quiz.
๐น File I/O in NumPy
np.savetxt('data.csv', arr, delimiter=',')
arr_loaded = np.loadtxt('data.csv', delimiter=',')
Real-Life Example:
Save and load data like marks, sales, or sensor values using CSV files.
๐ Interview Q&A with Real-Life Examples
1. What is NumPy? Why is it used?
Answer: A powerful library for numeric computations in Python. Used in data science, ML, and engineering.
Example: Analyze thousands of rows of Excel data in seconds.
2. Difference between Python list and NumPy array?
Feature | List | NumPy Array |
---|---|---|
Speed | Slow | Fast |
Memory | More | Less |
Operations | No vector ops | Vector ops |
Example: Process pixel data faster with NumPy. |
3. What is broadcasting?
Answer: It allows different-shaped arrays to work together in operations.
Example: Add 10% tax to each product price: arr + 10
4. How to create arrays?
Answer: Using np.array
, np.zeros
, np.ones
, np.arange
, etc.
Example: Initialize 0 attendance for all students.
5. What is reshape and flatten?
Answer: reshape()
changes shape, flatten()
converts to 1D.
Example: Convert a 2D image to 1D for model input.
6. Mathematical operations in NumPy?
Answer: Use +
, -
, *
, /
between arrays or scalars.
Example: Calculate final bill: price - discount
7. How to calculate statistics?
Answer: Use np.mean
, np.median
, np.std
, etc.
Example: Find average marks of a class.
8. Generating random numbers?
Answer: Use np.random.randint
, np.random.rand
, etc.
Example: Generate random test scores or sample data.
9. What is axis in NumPy?
Answer: Tells NumPy to operate along rows or columns.
Example: Sum all subjects per student: axis=1
10. File handling in NumPy?
Answer: np.savetxt
, np.loadtxt
for CSV operations.
Example: Save survey results into a CSV file.
Sure! Here’s a step-by-step NumPy guide with more examples and outputs, explained in simple English, including real-life usage.
๐งฎ NumPy Step-by-Step with Examples and Outputs
โ Step 1: Importing NumPy
import numpy as np
โ Why? This lets us use all the NumPy functions.
โ Step 2: Creating Arrays
โค 1D Array
a = np.array([1, 2, 3])
print(a)
# Output: [1 2 3]
โค 2D Array
b = np.array([[1, 2], [3, 4]])
print(b)
# Output:
# [[1 2]
# [3 4]]
โค 3D Array
c = np.array([[[1,2], [3,4]], [[5,6], [7,8]]])
print(c)
๐ฏ Real-Life Use: Store pixel values for an image (3D – width, height, channels).
โ Step 3: Array Properties
print(b.shape) # (2, 2)
print(b.ndim) # 2
print(b.size) # 4
print(b.dtype) # int64
๐ฏ Real-Life Use: Know the shape of Excel-like data before applying operations.
โ Step 4: Indexing and Slicing
arr = np.array([10, 20, 30, 40, 50])
print(arr[1:4])
# Output: [20 30 40]
โค 2D Indexing
arr2 = np.array([[1, 2], [3, 4]])
print(arr2[1, 0])
# Output: 3
๐ฏ Real-Life Use: Access student marks from rows and subjects from columns.
โ Step 5: Array Operations
a = np.array([10, 20, 30])
b = np.array([1, 2, 3])
print(a + b) # [11 22 33]
print(a * b) # [10 40 90]
๐ฏ Real-Life Use: Calculate bill amount = price * quantity
โ Step 6: Broadcasting
a = np.array([1, 2, 3])
print(a + 5)
# Output: [6 7 8]
๐ฏ Real-Life Use: Apply flat discount or tax to all items at once.
โ Step 7: Useful NumPy Functions
arr = np.array([10, 20, 30])
print(np.sum(arr)) # 60
print(np.mean(arr)) # 20.0
print(np.min(arr)) # 10
print(np.max(arr)) # 30
print(np.std(arr)) # 8.16...
๐ฏ Real-Life Use: Calculate total, average, and spread of exam scores.
โ Step 8: Reshape and Flatten
arr = np.array([[1, 2, 3], [4, 5, 6]])
reshaped = arr.reshape(3, 2)
print(reshaped)
# Output:
# [[1 2]
# [3 4]
# [5 6]]
flat = arr.flatten()
print(flat)
# Output: [1 2 3 4 5 6]
๐ฏ Real-Life Use: Prepare data for machine learning models (flat format).
โ Step 9: Stack and Split Arrays
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(np.hstack((a, b)))
# Output:
# [[1 2 5 6]
# [3 4 7 8]]
print(np.vstack((a, b)))
# Output:
# [[1 2]
# [3 4]
# [5 6]
# [7 8]]
๐ฏ Real-Life Use: Combine tables or reports horizontally/vertically.
โ Step 10: Random Numbers
np.random.seed(0)
print(np.random.randint(1, 10, (2, 3)))
# Output:
# [[5 6 1]
# [4 4 8]]
๐ฏ Real-Life Use: Create random test data or shuffle questions.
โ Step 11: Conditional Selection
arr = np.array([10, 20, 30, 40])
print(arr[arr > 20])
# Output: [30 40]
๐ฏ Real-Life Use: Filter students who scored above 20 marks.
โ Step 12: Save & Load Files
arr = np.array([[1, 2], [3, 4]])
np.savetxt("data.csv", arr, delimiter=",")
loaded = np.loadtxt("data.csv", delimiter=",")
print(loaded)
๐ฏ Real-Life Use: Save and reload reports, marks, or sales data.
โ Step 13: Axis in Functions
arr = np.array([[1, 2], [3, 4]])
print(np.sum(arr, axis=0)) # Column sum: [4 6]
print(np.sum(arr, axis=1)) # Row sum: [3 7]
๐ฏ Real-Life Use: Get total sales per product or per day.
โ Step 14: Special Arrays
print(np.zeros((2, 3))) # Array with all zeros
print(np.ones((2, 3))) # Array with all ones
print(np.eye(3)) # Identity matrix
๐ฏ Real-Life Use: Initialize tables, filters, or neural network layers.
โ Step 15: Linspace & Arange
print(np.linspace(1, 5, 5)) # [1. 2. 3. 4. 5.]
print(np.arange(1, 10, 2)) # [1 3 5 7 9]
๐ฏ Real-Life Use: Generate time steps or price intervals for charts.
๐ Final Thoughts
NumPy is essential for data analysis, machine learning, and scientific work in Python. Mastering it gives you speed, accuracy, and power to work with big data.
If youโre a beginner, practice real-life examples like:
- Student marks
- Sales data
- Weather sensor logs
Keep experimenting with arrays, slicing, operations, and reshaping to become a NumPy pro!
Leave a Reply