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 its 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]]
NumPy Insert Example
NumPy Insert Example
    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.
Aggregation Functions with Axis Explanation
NumPy Axis Explanation
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. Indexing and Slicing

    Question 1 of 5

      Store the 7-day average temperatures in a List as tmp_data = [22.2, 18.5, 20.4, 24.3, 21.9, 19.2, 21.1]. Assume first element is temperature of Monday
      1. Create a NumPy array from this list. Display newly created array, its shape and data type of its elements.
      2. Display the temperature for Wednesday.
      3. Replace the temperature for Friday with value -1.
      4. Display temperature from Tuesday to Thursday.
      5. Delete the temperature for Friday.
      6. Insert the temperature value for Friday again with median temperature.
      7. Display minimum and maximum temperature of week
  2. Modifying Arrays

    Question 2 of 5

      Assign course_data as [["Rabi", "Teacher"], ["Ram", "Student"], ["Shyam", "Student"]].
      1. Create a NumPy array from course_data.
      2. Display newly created array, its shape, and the data type (dtype) of its elements.
      3. Add a new row at the end for Sita with role Student and display the updated array.
      4. Add a new column named Age at the end with values 30, 25, 28, 22 and display the updated array.
      5. Delete the row for Ram, and display the updated array.
      6. Delete the Age column, and display the updated array.
      7. Add a new column named City as the second column with values Kathmandu, Mumbai, London and display the updated array.
      8. Display the names of all students.
      9. Display the role of Rabi.
      10. Display all information for Shyam.
  3. Vectorized Operation, Broadcast

    Question 3 of 5

      Assign cost_prices = [100, 150, 200, 250, 300]. Perform the following operations using NumPy.
      1. Create a NumPy array from cost_prices and assign it to cp_ar.
      2. Display cp_ar, its shape, and the data type (dtype) of its elements.
      3. Assuming a profit of 13% on the cost price, calculate the selling price for each product and assign the result to sp_ar.
      4. Calculate the profit for each product using sp_ar and cp_ar, and assign the result to profit_ar.
      5. Create function price_range(price) that categorizes a price as: - "low" if the price is below 150, - "medium" if the price is between 150 and 250 (inclusive), - "high" if the price is above 250.
      6. Vectorize the price_range function and assign it to price_range_vect.
      7. Use price_range_vect to determine price category for each selling price in sp_ar and assign the result to price_cat_ar.
      8. Convert all values in price_cat_ar into uppercase and assign the result to price_cat_upper.
      9. Display price_cat_upper.
      10. Create rev_ar by subtracting 2 from each element of profit_ar.
      11. Round each element of sp_ar upto two decimal places and assign the result to sp_ar_rounded.
      12. Display sp_ar, profit_ar, price_cat_ar, rev_ar, and sp_ar_rounded.
  4. Vectorized Operation, Broadcast

    Question 4 of 5

      Assign daily_deposit = [10, 15, 20, 25, 30, 27]
      1. Generate NumPy array from daily_deposit and assign it to deposit_ar.
      2. Generate total_amount_ar that stores the cumulative amount deposited each day.
      3. Display total_amount_ar. Expected output: [10 25 45 70 100 127]
      Assign co2_emission = [100, 150, 200, 250, 300]
      1. Create a NumPy array from co2_emission and assign it to co2_ar.
      2. Display co2_ar, its shape, and the data type (dtype) of its elements.
      3. Normalize the values in co2_ar so that they lie between 0 and 1 using the formula: x_norm = (x - min) / (max - min) and assign result to co2_norm_ar.
      4. Display co2_norm_ar.
      Assign salary = [800, 1200, 3000, 6000]
      1. Create a NumPy array from salary and assign it to salary_ar.
      2. Display salary_ar, its shape, and the data type (dtype) of its elements.
      3. Create a function increment_salary(salary) that returns the revised salary based on the following hike rules: - Salary below 1000: increase by 20% - Salary from 1000 to 5000(inclusive): increase by 10% - Salary above 5000: increase by 5%
      4. Vectorize increment_salary and store as increment_salary_vect.
      5. Apply increment_salary_vect, to salary_ar for increasing salary and assign the result as new_salary_ar
      6. Display new_salary_ar.
  5. Aggregate Functions

    Question 5 of 5

      Assign marks_ar = [[80, 90, 70], [60, 75, 85], [90, 95, 100]]. In given 2D array, each row represents marks scored by individual student and column represents marks obtained in Maths, Science and Programming. Find the following:
      1. Total marks of obtained by each students.
      2. Average marks obtained by each students.
      3. Minimum and maximum marks of each students.
      4. Highest score in Science subject.
      5. Lowest score in Maths subject.
      6. Average score of each subject
Advertisement
Ad PlaceholderSlot: 5413242224