NumPy: Basics

βœ•

1. Introduction

    1.1 πŸ₯š What is NumPy?
    1. NumPy stands for Numerical Python. It is a Python library that helps us work with many numbers quickly and easily. Think of NumPy like an egg tray for numbers. πŸ‘‰ A Python list is like carrying eggs one by one. πŸ‘‰ A NumPy array is like carrying the whole egg tray at once. This makes NumPy faster and easier when working with large amounts of numerical data. With NumPy, we can add, multiply, compare, and summarize many numbers in one step.
NumPy Array Analogy
NumPy Array Analogy
    1.2 πŸ’» Why Use NumPy?
    1. NumPy is useful because: βœ… It is faster for mathematical operations βœ… It works well with Data Science tools like Pandas and Scikit-Learn βœ… It has many built-in functions for math, statistics, and arrays βœ… It supports vectorized operations, so we can avoid writing many loops πŸ“Œ NumPy helps us work with numbers faster and smarter.

2. Core Concepts

    2.1 πŸ”’ ndarray
    1. The main object in NumPy is called an ndarray. ndarray means N-dimensional array. A NumPy array: πŸ‘‰ Stores many values together πŸ‘‰ Stores values of the same data type πŸ‘‰ Has shape, size, and data type
2.2 πŸ“ 1D, 2D, and 3D Arrays
Array TypeSimple MeaningReal-Life Example
1D ArrayA single row of valuesRow of boxes
2D ArrayRows and columnsEgg tray or table
3D ArrayMultiple layersRubik's cube
Representation of NumPy 1D, 2D, and 3D Arrays
NumPy 1D, 2D, and 3D Arrays

3. Creating NumPy Arrays

    3.1 Creating Arrays from Lists and Tuples
    1. We can create NumPy arrays from Python lists or tuples. If values have different data types, NumPy may convert them into a common data type. For example, if we mix integers and floats, NumPy converts all values to float. From List import numpy as npmy_list = [1, 2, 3]my_array = np.array(my_list) # We can also use np.asarray(my_list)print(my_array) # [1 2 3] print(type(my_array)) # <class numpy.ndarray> From Tuple import numpy as npmy_tuple = (4, 5, 6)my_array = np.array(my_tuple, dtype=float) print(my_array) # [4. 5. 6.] Creating 2D Array import numpy as npmy_2d_list = [[1, 2], [3, 4]]my_2d_array = np.array(my_2d_list) print(my_2d_array)Output [[1 2] [3 4]]
    3.2 Inspecting Array Properties
    1. We can inspect NumPy arrays using shape, size, dtype. Example import numpy as nparr = np.array([[1, 2, 5], [3, 4, 7]]) # [[1 2 5] # [3 4 7]] print(arr.shape) # (2, 3) print(arr.dtype) # int64 or int32 print(arr.size) # 6 πŸ“Œ These properties help us understand the structure of an array.
NumPy Array Properties
NumPy Array Properties
Array Property Reference
PropertyMeaning
shapeNumber of rows and columns
sizeTotal number of elements
dtypeData type of elements

4. Accessing Elements in NumPy Arrays

    4.1 Indexing
    1. Indexing means selecting a specific element from an array. Like Python lists, NumPy indexing starts from 0. We can also use negative indexing. Index: 1D Array import numpy as nparr = np.array([10, 20, 30, 40, 50])print(arr[0]) # 10 print(arr[2]) # 30 print(arr[-1]) # 50 print(arr[-2]) # 40 We can also update values: arr[-1] = 80 print(arr) # [10 20 30 40 80] Index: 2D Array import numpy as nparr_2d = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9] ])print(arr_2d[0]) # First row: [1 2 3] print(arr_2d[1, 2]) # 2nd row, 3rd column: 6 print(arr_2d[-1, -2]) # Last row, 2nd last column: 8 Updating a value: arr_2d[0, 0] = 10 print(arr_2d)Output: [[10 2 3] [ 4 5 6] [ 7 8 9]]
NumPy Indexing and Slicing
NumPy Indexing and Slicing
    4.2 Slicing
    1. Slicing means selecting a part of an array. Syntax: array[start:stop] start is included stop is not included Slicing: 1D Array import numpy as nparr = np.array([10, 20, 30, 40, 50])print(arr[1:4]) # [20 30 40] print(arr[:3]) # [10 20 30] print(arr[2:]) # [30 40 50] print(arr[-3:-1]) # [30 40] For slicing a 2D array, we first slice by row and then by column. The slicing before , is for rows, and the slicing after , is for columns. Example import numpy as nparr_2d = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9] ])print(arr_2d[0:2]) # Sub-matrix with row 0 and 1 Output: [[1 2 3] [4 5 6]] Select All rows and first two columns: print(arr_2d[:, :2])Output: [[1 2] [4 5] [7 8]] Select rows from index 1 to end and last column: print(arr_2d[1:, -1])Output: [6 9]

5. Adding Elements to NumPy Arrays

    5.1 np.insert
    1. np.insert() adds values at a specific index. Insert on 1D Array import numpy as nparr = np.array([3, 5, 8, 2, 7])new_arr = np.insert(arr, 2, 10) print(new_arr)Output: [ 3 5 10 8 2 7] For 2D array, we can either add new row or column. axis is used to determine whether to add on row or on column. axis=0 indicates new row has to be added and axis=1 indicates new column has to be added. Example: Add Row in 2D Array import numpy as nparr_2d = np.array([[1, 2], [3, 4]])new_arr = np.insert(arr_2d, 1, [5, 6], axis=0) print(new_arr)Output: [[1 2] [5 6] [3 4]] Example: Add Column in 2D Array import numpy as nparr_2d = np.array([[1, 2], [3, 4]])new_arr = np.insert(arr_2d, 1, [5, 6], axis=1) print(new_arr)Output: [[1 5 2] [3 6 4]]
    5.2 np.append
    1. np.append() adds values at the end of an array. For 2D array similar to np.insert, we use axis parameter to control whether to add at last row or add at last column. For 2D arrays, the new row or column should also be given in 2D format. Append: 1D Array import numpy as nparr = np.array([1, 2, 3]) new_arr = np.append(arr, [4, 5]) print(new_arr)Output: [1 2 3 4 5] Append: Add Row in 2D Array import numpy as nparr_2d = np.array([[1, 2], [3, 4]]) new_arr = np.append(arr_2d, [[5, 6]], axis=0)print(new_arr)Output: [[1 2] [3 4] [5 6]] Example: Add Column in 2D Array import numpy as nparr_2d = np.array([[1, 2], [3, 4]]) new_arr = np.append(arr_2d, [[5], [6]], axis=1) print(new_arr)Output: [[1 2 5] [3 4 6]]

6. Removing Elements

    6.1 np.delete
    1. np.delete() removes values from an array. We can specify the index which needs to be dropped. For 2-D, axis=0 drops row and axis=1 drops column. Example: 1D Array import numpy as nparr = np.array([10, 20, 30, 40, 50]) new_arr = np.delete(arr, 2) print(new_arr)Output: [10 20 40 50] Example: Remove Row from 2D Array import numpy as nparr_2d = np.array([[1, 2], [3, 4], [5, 6]]) new_arr = np.delete(arr_2d, 1, axis=0) print(new_arr)Output: [[1 2] [5 6]] Example: Remove Column from 2D Array import numpy as nparr_2d = np.array([[1, 2], [3, 4], [5, 6]]) new_arr = np.delete(arr_2d, 0, axis=1) print(new_arr)Output: [[2] [4] [6]]
NumPy Delete Example
NumPy Delete Example

7. Vectorized Operations

    7.1 Array with Constants
    1. Vectorized operations apply an operation to every element of an array. This means we do not need to write loops. Common operations include: +, -, *, /, **, //, %, <, <=, >, >=, ==, !=Example import numpy as nparr = np.array([1, 2, 3, 4])print(arr + 10) # [11 12 13 14] print(arr * 2) # [2 4 6 8] print(arr > 2) # [False False True True] print((arr % 2 == 0) & (arr > 2)) # [False False False True] πŸ“Œ NumPy applies the operation to all elements at once.
    7.2 Array with Array
    1. When two arrays have the same shape, NumPy applies operations element-wise. Example import numpy as nparr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6])print(arr1 + arr2) # [5 7 9] print(arr1 * arr2) # [ 4 10 18] print(arr1 > arr2) # [False False False]
    7.3 Matrix Multiplication
    1. For matrix multiplication, use @. import numpy as npmat_a = np.array([[1, 2], [3, 4]]) mat_b = np.array([[5, 6], [7, 8]])print(mat_a @ mat_b)Output: [[19 22] [43 50]] πŸ“Œ Important: * performs element-wise multiplication, but @ performs matrix multiplication.
NumPy Element-wise vs Matrix Multiplication
NumPy Element-wise vs Matrix Multiplication

8. Mathematical Functions

    8.1 Applying Math Functions
    1. NumPy provides many mathematical functions. These functions usually work element-wise. Example import numpy as npa1 = np.array([2, 5.2, 8.7])print(np.sqrt(a1)) # Square root print(np.power(a1, 2)) # Square print(np.sin(a1)) # Sine value print(np.round(a1, 2)) # Round to 2 decimals print(np.abs(a1)) # Absolute value print(np.radians(a1)) # Degrees to radians print(np.degrees(a1)) # Radians to degrees πŸ“Œ NumPy math functions can work on the whole array at once.
Common Math Functions
FunctionMeaning
np.sqrt()Square root of each element
np.power()Raise each element to a power
np.sin()Sine of each element
np.round()Round values
np.abs()Absolute value
np.radians()Convert degrees to radians
np.degrees()Convert radians to degrees

9. String Functions: np.char

    9.1 Applying String Functions
    1. NumPy also supports string operations using np.char. These functions work element-wise on string arrays. Example import numpy as nps1 = np.array(["hi ", " all"])print(np.char.upper(s1)) # ["HI " " ALL"] print(np.char.title(s1)) # ["Hi " " All"] print(np.char.strip(s1)) # ["hi" "all"] print(np.char.replace(s1, " ", "_")) # ["hi_" "_all"] print(np.char.split(s1)) # [["hi"] ["all"]] print(np.char.find(s1, "h")) # [0 -1] print(np.char.count(s1, "l")) # [0 2] print(np.char.str_len(s1)) # [3 4]
Common String Functions
FunctionMeaning
np.char.upper()Convert strings to uppercase
np.char.lower()Convert strings to lowercase
np.char.title()Convert strings to title case
np.char.strip()Remove extra spaces
np.char.replace()Replace one text with another
np.char.split()Split strings
np.char.find()Find index of text
np.char.count()Count text occurrences
np.char.str_len()Find string length
np.char.startswith()Check if string starts with text
np.char.endswith()Check if string ends with text

10. Aggregate Functions

    10.1 What are Aggregate Functions?
    1. Aggregate functions summarize data. They help answer questions like: ❓What is the total? ❓What is the average? ❓What is the minimum? ❓What is the maximum? We can aggregate the whole array, or aggregate by rows and columns using the axis parameter. Example: Whole Array import numpy as npa2 = np.array([[1, 2], [3, 4]])print(np.sum(a2)) print(np.mean(a2)) print(np.median(a2)) print(np.std(a2)) print(np.var(a2)) print(np.min(a2)) print(np.max(a2)) print(np.argmin(a2)) print(np.argmax(a2)) print(np.clip(a2, 2, 3)) print(np.cumsum(a2)) print(np.ptp(a2)) print(np.quantile(a2, 0.5))Example: Along Axis import numpy as npa2 = np.array([[1, 2], [3, 4]])print(np.sum(a2, axis=0)) # Column-wise sum [4 6] print(np.mean(a2, axis=1)) # Row-wise mean [1.5 3.5] πŸ“Œ Aggregate functions help summarize data quickly.
    10.2 Axis Meaning
    1. For a 2D array: axis=0 means column-wise operation ↓. axis=1 means row-wise operation β†’. πŸ“Œ Axis controls the direction of calculation.
NumPy Insert Example
NumPy Insert Example
Common Aggregate Functions
FunctionMeaning
np.sum()Total of values
np.mean()Average
np.median()Middle value
np.std()Standard deviation
np.var()Variance
np.min()Minimum value
np.max()Maximum value
np.argmin()Index of minimum value
np.argmax()Index of maximum value
np.clip()Limit values within a range
np.cumsum()Cumulative sum
np.cumprod()Cumulative product
np.ptp()Range: max - min
np.quantile()Quantile value
np.cov()Covariance

11. Applying Custom Functions to NumPy Arrays

    11.1 np.vectorize
    1. np.vectorize() is a convenient way to apply our own function to every element of a NumPy array. Example import numpy as npdef can_have_license(age):return age >= 16vectorized_license_check = np.vectorize(can_have_license) ages = np.array([10, 16, 18, 12]) result = vectorized_license_check(ages) print(result) # [False True True False] πŸ“Œ np.vectorize() helps apply a custom function to each value in an array.

12. NumPy Constants

    12.1 Common NumPy Constants
    1. NumPy provides some useful mathematical constants.
Common NumPy Constants
ConstantMeaningValue
np.piValue of pi Ο€3.141592653589793
np.infPositive infinityinf
-np.infNegative infinity-inf
np.nanNot a Numbernan
    12.2 Example
    1. import numpy as npprint(np.pi) print(np.inf) print(-np.inf) print(np.nan) πŸ“Œ These constants are useful in math, statistics, and data cleaning.
Advertisement
Ad PlaceholderSlot: 7421026683

Practice QuestionsNot started

  1. 1. NumPy Practice Tasks

    Question 1 of 1

      1.1 Create and inspect
      1. Create array 1..20, reshape to (4,5). Print shape, dtype, and element at row 2 col 3.
      1.2 Indexing & slicing
      1. Given arr = np.array([10,20,30,40,50]), show last element, reversed array, and every 2nd element.
      1.3 Modify arrays
      1. Insert 10 at index 1 in [1,2,3]. Append 4. Delete index 2.
      1.4 Vector math
      1. a = np.array([2,4,6]), b = np.array([1,1,1]). Compute a*b, a/b, a**2.
      1.5 Broadcasting
      1. Create M shape (3,4) with 1..12. Add [0,10,20,30].
      1.6 Aggregates & stats
      1. Given x = np.random.rand(1000), compute mean, min, max, std, and 25th percentile.
      1.7 Strings
      1. Given s = np.array([" hello ", "world"]), strip spaces and uppercase.
      1.8 Linear algebra
      1. Compute determinant and inverse of [[1,2],[3,4]].
Advertisement
Ad PlaceholderSlot: 5413242224