Piyush Ranjan
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Numpy 2 --- title: Agenda description: duration: 300 card_type: cue_card --- ### Content - Working with 2D arrays (Matrices) - Transpose - Indexing - Slicing - Fancy Indexing (Masking) - Aggregate Functions - Logical Operations - `np.any()` - `np.all()` - `np.where()` - Use Case: Fitness data analysis --- title: Working with 2-D arrays (Matrices) description: duration: 1200 card_type: cue_card --- ## Working with 2-D arrays (Matrices Let's create an array - Code ``` python= a = np.array(range(16)) a ``` > **Output** ``` array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) ``` What will be it's shape and dimensions? Code ``` python= a.shape ``` > **Output** ``` (16,) ``` Code ``` python= a.ndim ``` > **Output** ``` 1 ``` ### How can we convert this to a 2-dimensional array? - Using `reshape()` For a 2D array, we will have to specify the following:- - **First argument** is **no. of rows** - **Second argument** is **no. of columns** Let's try converting it into a 8x2 array. Code ``` python= a.reshape(8, 2) ``` > **Output** ``` array([[ 0, 1], [ 2, 3], [ 4, 5], [ 6, 7], [ 8, 9], [10, 11], [12, 13], [14, 15]]) ``` Let's try converting it into a `4x4` array. Code ``` python= a.reshape(4, 4) ``` > **Output** ``` array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) ``` Code ``` python= a.reshape(4, 5) ``` > **Output** ``` --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-14-05ad01dfd0f5> in <cell line: 1>() ----> 1 a.reshape(4, 5) ValueError: cannot reshape array of size 16 into shape (4,5) ``` **This will give an Error. Why?** * We have 16 elements in `a`, but `reshape(4, 5)` is trying to fill in `4 x 5 = 20` elements. * Therefore, whatever the shape we're trying to reshape to, must be able to incorporate the number of elements we have. Code ``` python= a.reshape(8, -1) ``` > **Output** ``` array([[ 0, 1], [ 2, 3], [ 4, 5], [ 6, 7], [ 8, 9], [10, 11], [12, 13], [14, 15]]) ``` Notice that Python automatically figured out, that what should be the replacement of `-1` argument, given that the first argument is `8`. We can also put `-1` as the first argument. As long as one argument is given, it will calculate the other one. **What if we pass both args as `-1`?** Code ``` python= a.reshape(-1, -1) ``` > **Output** ``` --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-18-decf4fe03d74> in <cell line: 1>() ----> 1 a.reshape(-1, -1) ValueError: can only specify one unknown dimension ``` Error. You need to give at least one dimension. Let's save `a` as a `8 x 2` array (Matrix). Code ``` python= a = a.reshape(8, 2) ``` **What will be the length of `a`?** * It will be 8, since it contains 8 lists as it's elements. * Each of these lists have 2 elements, but that's a different thing. **Explanation: `len(nD array)` will give you magnitude of first dimension** Code ``` python= len(a) ``` > **Output** ``` 8 ``` Code ``` python= len(a[0]) ``` > **Output** ``` 2 ``` ### Transpose Let's create a 2-D numpy array. Code ``` python= a = np.arange(12).reshape(3,4) a ``` > **Output** ``` array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) ``` Code ``` python= a.shape ``` > **Output** ``` (3, 4) ``` There is another operation on a multi-dimensional array, known as **Transpose**. It basically means that the no. of rows is interchanged by no. of cols,and vice-versa. Code ``` python= a.T ``` > **Output** ``` array([[ 0, 4, 8], [ 1, 5, 9], [ 2, 6, 10], [ 3, 7, 11]]) ``` Let's verify the shape of this transpose - Code ``` python= a.T.shape ``` >Output ``` (4, 3) ``` --- title: Indexing in 2D arrays description: duration: 900 card_type: cue_card --- ## Indexing in 2D arrays - Similar to Python lists <img src = https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/054/693/original/2dnp.png?1697949471 height = "500" width = "700"> Code ```python= a ``` >Output ``` array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) ``` **Can we extract just the element `6` from `a`?** Code ``` python= # Accessing 2nd row and 3rd col a[1, 2] ``` > **Output** ``` 6 ``` This can also be written as: Code ``` python= a[1][2] ``` > **Output** ``` 6 ``` Code ``` python= m1 = np.arange(1,10).reshape((3,3)) m1 ``` > **Output** ``` array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) ``` **What will be the output of this?** Code ``` python= m1[1,1] ``` > **Output** ``` 5 ``` We saw how we can use list of indexes in numpy array. **Will this work now?** Code ``` python= m1 = np.array([100,200,300,400,500,600]) m1[2, 3] ``` > **Output** ``` --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-36-963ce94bbe14> in <cell line: 1>() ----> 1 m1[2, 3] IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed ``` **Note:** - Since `m1` is a 1D array, this will not work. - This is because there are no row and column entity here. Therefore, you cannot use the same syntax for 1D arrays, as you did with 2D arrays, and vice-versa. However with a little tweak in this code, we can access elements of `m1` at different positions/indices. Code ``` python= m1[[2, 3]] ``` > **Output** ``` array([300, 400]) ``` #### How will you print the diagonal elements of the following 2D array Code ``` python= m1 = np.arange(9).reshape((3,3)) m1 ``` > **Output** ``` array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) ``` Code ``` python= m1[[0,1,2],[0,1,2]] # picking up element (0,0), (1,1) and (2,2) ``` > **Output** ``` array([0, 4, 8]) ``` When list of indexes is provided for both rows and cols, for example: `m1[[0,1,2],[0,1,2]]` It selects individual elements i.e. `m1[0][0], m1[1][1] and m2[2][2]`. --- title: Slicing in 2D arrays description: duration: 900 card_type: cue_card --- ## Slicing in 2D arrays - Need to **provide two slice ranges**, one for **row** and one for **column**. - We can also **mix Indexing and Slicing** Code ``` python= m1 = np.arange(12).reshape(3,4) m1 ``` > **Output** ``` array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) ``` Code ``` python= m1[:2] # gives first two rows ``` > **Output** ``` array([[0, 1, 2, 3], [4, 5, 6, 7]]) ``` #### How can we get columns from 2D array? Code ``` python= m1[:, :2] # gives first two columns ``` > **Output** ``` array([[0, 1], [4, 5], [8, 9]]) ``` Code ``` python= m1[:, 1:3] # gives 2nd and 3rd col ``` > **Output** ``` array([[ 1, 2], [ 5, 6], [ 9, 10]]) ``` --- title: Quiz-1 description: Quiz-1 duration: 60 card_type: quiz_card --- # Question What will be the output of the following code? ```python= a = [1,2,3,4,5] b = [8,7,6] a[3:] = b[::-2] print(a) ``` # Choices - [ ] [1,2,6,7,8] - [x] [1,2,3,6,8] - [ ] [1,2,3,4,5,8,7,6] --- title: Fancy Indexing (Masking) in 2D arrays description: duration: 900 card_type: cue_card --- ## Fancy Indexing (Masking) in 2D arrays We did this for one dimensional arrays. Let's see if those concepts translate to 2D also. Suppose we have following matrix `m1` - Code ``` python= m1 = np.arange(12).reshape(3, 4) m1 ``` > **Output** ``` array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) ``` **What will be output of following?** Code ``` python= m1 < 6 ``` > **Output** ``` array([[ True, True, True, True], [ True, True, False, False], [False, False, False, False]]) ``` - A **matrix having boolean values** `True` and `False` is returned. - **We can use this boolean matrix to filter our array.** **Condition will be passed instead of indices and slice ranges.** Code ``` python= m1[m1 < 6] # Value corresponding to True is retained # Value corresponding to False is filtered out ``` > **Output** ``` array([0, 1, 2, 3, 4, 5]) ``` --- title: Quiz-2 description: Quiz-2 duration: 60 card_type: quiz_card --- # Question What will be the value of `a`? ```python= a = np.array([0,1,2,3,4,5]) mask = (a%2 == 0) a[mask] = -1 ``` # Choices - [ ] [0,1,2,3,4,5] - [ ] [-1,1,-1,1,-1,1] - [x] [-1,1,-1,3,-1,5] --- title: Aggregate Functions description: duration: 1800 card_type: cue_card --- ## Aggregate Functions Numpy provides various universal functions that cover a wide variety of operations and perform **fast element-wise array operations**. #### How would you calculate the sum of elements of an array? #### `np.sum()` - **It sums all the values in a np array**. Code ``` python= a = np.arange(1, 11) a ``` > **Output** ``` array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) ``` Code ``` python= np.sum(a) # sums all the values present in array ``` > **Output** ``` 55 ``` #### Now, what if we want to find the average value or median value of all the elements in an array? #### `np.mean()` - **It gives the us mean of all values in a np array**. Code ``` python= np.mean(a) # mean/average value ``` > **Output** ``` 5.5 ``` #### Now, we want to find the minimum / maximum value in the array. #### `np.min()` / `np.max()` Code ```python= np.min(a) ``` > **Output** 1 Code ```python= np.max(a) ``` > **Output** 10 Let's apply aggregate functions on 2D array. Code ``` python= a = np.arange(12).reshape(3, 4) a ``` > **Output** ``` array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) ``` Code ``` python= np.sum(a) # sums all the values present in array ``` > **Output** ``` 66 ``` ### What if we want to do the elements row-wise or column-wise? - By **setting `axis` parameter** #### What will `np.sum(a, axis=0)` do? - `np.sum(a, axis=0)` adds together values in **different rows** - `axis = 0` $\rightarrow$ **Changes will happen along the vertical axis** - Summation of values happen **in the vertical direction**. - Rows collapse/merge when we do `axis=0`. Code ``` python= np.sum(a, axis=0) ``` > **Output** ``` array([12, 15, 18, 21]) ``` ### Now, what if we specify `axis=1`? - `np.sum(a, axis=1)` adds together values in **different columns** - `axis = 1` $\rightarrow$ **Changes will happen along the horizontal axis** - Summation of values happen **in the horizontal direction**. - Columns collapse/merge when we do `axis=1`. Code ``` python= np.sum(a, axis=1) ``` > **Output** ``` array([ 6, 22, 38]) ``` --- title: Break & Doubt Resolution description: duration: 600 card_type: cue_card --- ### Break & Doubt Resolution `Instructor Note:` * Take this time (up to 5-10 mins) to give a short break to the learners. * Meanwhile, you can ask the them to share their doubts (if any) regarding the topics covered so far. --- title: Logical Operations description: duration: 1800 card_type: cue_card --- ## Logical Operations #### What if we want to check whether **"any"** element of array follows a specific condition? #### `np.any()` can become handy here as well - `any()` returns `True` if **any of the corresponding elements** in the argument arrays follow the **provided condition**. \ Imagine you have a shopping list with items you need to buy, but you're not sure if you have enough money to buy everything. You want to check if there's at least one item on your list that you can afford. In this case, you can use `np.any`: Code ``` python= import numpy as np # Prices of items on your shopping list prices = np.array([50, 45, 25, 20, 35]) # Your budget budget = 30 # Check if there's at least one item you can afford can_afford = np.any(prices <= budget) if can_afford: print("You can buy at least one item on your list!") else: print("Sorry, nothing on your list fits your budget.") ``` > **Output** ``` You can buy at least one item on your list! ``` #### What if we want to check whether "all" the elements in our array follow a specific condition? #### `np.all()` Let's consider a scenario where you have a list of chores, and you want to make sure all the chores are done before you can play video games. You can use `np.all` to check if all the chores are completed. Code ``` python= import numpy as np # Chores status: 1 for done, 0 for not done chores = np.array([1, 1, 1, 1, 0]) # Check if all chores are done all_chores_done = np.all(chores == 1) if all_chores_done: print("Great job! You've completed all your chores. Time to play!") else: print("Finish all your chores before you can play.") ``` > **Output** ``` Finish all your chores before you can play. ``` #### Multiple conditions for `.all()` function Code ``` python= a = np.array([1, 2, 3, 2]) b = np.array([2, 2, 3, 2]) c = np.array([6, 4, 4, 5]) ((a <= b) & (b <= c)).all() ``` > **Output** True #### What if we want to update an array based on condition? Suppose you are given an array of integers and you want to update it based on following condition : - if element is > 0, change it to +1 - if element < 0, change it to -1. **How will you do it?** Code ``` python= arr = np.array([-3,4,27,34,-2, 0, -45,-11,4, 0 ]) arr ``` > **Output** ``` array([ -3, 4, 27, 34, -2, 0, -45, -11, 4, 0]) ``` You can use masking to update the array. ``` python= arr[arr > 0] = 1 arr [arr < 0] = -1 arr ``` > **Output** ``` array([-1, 1, 1, 1, -1, 0, -1, -1, 1, 0]) ``` There's also a numpy function which can help us with it. #### `np.where()` - Syntax: `np.where(condition, [x, y])` - returns an `ndarray` whose elements are chosen from `x` or `y` depending on condition. Suppose you have a list of product prices, and you want to apply a **10%** discount to all products with prices above **$50**. You can use `np.where` to adjust the prices. Code ``` python= import numpy as np # Product prices prices = np.array([45, 55, 60, 75, 40, 90]) # Apply a 10% discount to prices above $50 discounted_prices = np.where(prices > 50, prices * 0.9, prices) print("Original prices:", prices) print("Discounted prices:", discounted_prices) ``` > **Output** ``` Original prices: [45 55 60 75 40 90] Discounted prices: [45. 49.5 54. 67.5 40. 81. ] ``` **Notice that it didn't change the original array.** --- title: Quiz-3 description: Quiz-3 duration: 60 card_type: quiz_card --- # Question What will be the output of `a >= b` ? ```python= a = np.array([0,2,3]) b = np.array([1,3,5]) ``` # Choices - [ ] True - [ ] False - [x] [False, False, False] --- title: Quiz-4 description: Quiz-4 duration: 60 card_type: quiz_card --- # Question What will be the output of following code? ```python= arr = np.array([-3,4,27,34,-2, 0, -45,-11,4, 0]) print(np.where(arr)) ``` # Choices - [ ] [-3, -2, -45, -11] - [x] [0, 1, 2, 3, 4, 6, 7, 8] - [ ] [4, 27, 34 , 0, 4, 0] --- title: Use Case - Fitness data analysis description: duration: 1800 card_type: cue_card --- ## Use Case: Fitness data analysis Imagine you are a Data Scientist at Fitbit You've been given a user data to analyse and find some insights which can be shown on the smart watch. But why would we want to analyse the user data for desiging the watch? These insights from the user data can help business make customer oriented decision for the product design. Let's first look at the data we have gathered. <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/047/697/original/Image_3.png?1694433382" width=500 height=300 > Notice that our data is structured in a tabular format. - Each column is known as a feature. - Each row is known as a record. ### Basic EDA Performing **Exploratory Data Analysis (EDA)** is like being a detective for numbers and information. Imagine you have a big box of colorful candies. EDA is like looking at all the candies, counting how many of each color there are, and maybe even making a pretty picture to show which colors you have the most of. This way, you can learn a lot about your candies without eating them all at once! <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/047/698/original/Image_4.png?1694433518" width="400" height="300"> So, EDA is about looking at your things, which is data in this case, to understand them better and find out interesting stuff about them. Formally defining, Exploratory Data Analysis (EDA) is a process of **examining**, **summarizing**, and **visualizing** data sets to understand their main characteristics, uncover patterns that helps analysts and data scientists gain insights into the data, make informed decisions, and guide further analysis or modeling. First, we will import numpy. ``` python= import numpy as np ``` **Let's load the data that we saw earlier.** For this we will use `.loadtxt()` function. Code ``` python= !gdown https://drive.google.com/uc?id=1vk1Pu0djiYcrdc85yUXZ_Rqq2oZNcohd ``` > **Output** ``` Downloading... From: https://drive.google.com/uc?id=1vk1Pu0djiYcrdc85yUXZ_Rqq2oZNcohd To: /content/fit.txt 0% 0.00/3.43k [00:00<?, ?B/s] 100% 3.43k/3.43k [00:00<00:00, 13.1MB/s] ``` Code ``` python= data = np.loadtxt('/content/fit.txt', dtype='str') ``` We provide file name along with the dtype of data we want to load in. What's the shape of the data? Code ``` python= data.shape ``` > **Output** ``` (96, 6) ``` What's the dimensionality? Code ``` python= data.ndim ``` > **Output** ``` 2 ``` We can see that this is a 2-dimensional list. There are 96 records and each record has 6 features. These features are: - Date - Step Count - Mood - Calories Burned - Hours of Sleep - Activity Status **Notice that above array is homogenous containing all the data as strings.** In order to work with strings, categorical data and numerical data, we'll have to save every feature seperately. \ **How will we extract features in seperate variables?** For that, we first need some idea on how data is saved. Let's see whats the first element of the `data`. Code ``` python data[0] ``` > **Output** ``` array(['06-10-2017', '5464', 'Neutral', '181', '5', 'Inactive'], dtype='<U10') ``` Hmm.. this extracts a row, not a column. Similarly, we can extract other specific rows. Code ``` python= data[1] ``` > **Output** ``` array(['07-10-2017', '6041', 'Sad', '197', '8', 'Inactive'], dtype='<U10') ``` We can also use slicing. Code ``` python= data[:5] ``` > **Output** ``` array([['06-10-2017', '5464', 'Neutral', '181', '5', 'Inactive'], ['07-10-2017', '6041', 'Sad', '197', '8', 'Inactive'], ['08-10-2017', '25', 'Sad', '0', '5', 'Inactive'], ['09-10-2017', '5461', 'Sad', '174', '4', 'Inactive'], ['10-10-2017', '6915', 'Neutral', '223', '5', 'Active']], dtype='<U10') ``` ### Fitbit Solution Now, we want to place all the **dates** into a single entity. **How to do that?** - One way is to just go ahead and fetch the column number 0 from all rows. - Another way is to, take a transpose of `data`. Let's see them both - > **Approach 1** Code ``` python= data[:, 0] ``` >Output ``` array(['06-10-2017', '07-10-2017', '08-10-2017', '09-10-2017', '10-10-2017', '11-10-2017', '12-10-2017', '13-10-2017', '14-10-2017', '15-10-2017', '16-10-2017', '17-10-2017', '18-10-2017', '19-10-2017', '20-10-2017', '21-10-2017', '22-10-2017', '23-10-2017', '24-10-2017', '25-10-2017', '26-10-2017', '27-10-2017', '28-10-2017', '29-10-2017', '30-10-2017', '31-10-2017', '01-11-2017', '02-11-2017', '03-11-2017', '04-11-2017', '05-11-2017', '06-11-2017', '07-11-2017', '08-11-2017', '09-11-2017', '10-11-2017', '11-11-2017', '12-11-2017', '13-11-2017', '14-11-2017', '15-11-2017', '16-11-2017', '17-11-2017', '18-11-2017', '19-11-2017', '20-11-2017', '21-11-2017', '22-11-2017', '23-11-2017', '24-11-2017', '25-11-2017', '26-11-2017', '27-11-2017', '28-11-2017', '29-11-2017', '30-11-2017', '01-12-2017', '02-12-2017', '03-12-2017', '04-12-2017', '05-12-2017', '06-12-2017', '07-12-2017', '08-12-2017', '09-12-2017', '10-12-2017', '11-12-2017', '12-12-2017', '13-12-2017', '14-12-2017', '15-12-2017', '16-12-2017', '17-12-2017', '18-12-2017', '19-12-2017', '20-12-2017', '21-12-2017', '22-12-2017', '23-12-2017', '24-12-2017', '25-12-2017', '26-12-2017', '27-12-2017', '28-12-2017', '29-12-2017', '30-12-2017', '31-12-2017', '01-01-2018', '02-01-2018', '03-01-2018', '04-01-2018', '05-01-2018', '06-01-2018', '07-01-2018', '08-01-2018', '09-01-2018'], dtype='<U10') ``` This gives all the dates. > **Approach 2** Code ``` python= data_t = data.T ``` Don't you think all the dates will now be present in the first (i.e. index 0th element) of `data_t`? Code ``` python= data_t[0] ``` > **Output** ``` array(['06-10-2017', '07-10-2017', '08-10-2017', '09-10-2017', '10-10-2017', '11-10-2017', '12-10-2017', '13-10-2017', '14-10-2017', '15-10-2017', '16-10-2017', '17-10-2017', '18-10-2017', '19-10-2017', '20-10-2017', '21-10-2017', '22-10-2017', '23-10-2017', '24-10-2017', '25-10-2017', '26-10-2017', '27-10-2017', '28-10-2017', '29-10-2017', '30-10-2017', '31-10-2017', '01-11-2017', '02-11-2017', '03-11-2017', '04-11-2017', '05-11-2017', '06-11-2017', '07-11-2017', '08-11-2017', '09-11-2017', '10-11-2017', '11-11-2017', '12-11-2017', '13-11-2017', '14-11-2017', '15-11-2017', '16-11-2017', '17-11-2017', '18-11-2017', '19-11-2017', '20-11-2017', '21-11-2017', '22-11-2017', '23-11-2017', '24-11-2017', '25-11-2017', '26-11-2017', '27-11-2017', '28-11-2017', '29-11-2017', '30-11-2017', '01-12-2017', '02-12-2017', '03-12-2017', '04-12-2017', '05-12-2017', '06-12-2017', '07-12-2017', '08-12-2017', '09-12-2017', '10-12-2017', '11-12-2017', '12-12-2017', '13-12-2017', '14-12-2017', '15-12-2017', '16-12-2017', '17-12-2017', '18-12-2017', '19-12-2017', '20-12-2017', '21-12-2017', '22-12-2017', '23-12-2017', '24-12-2017', '25-12-2017', '26-12-2017', '27-12-2017', '28-12-2017', '29-12-2017', '30-12-2017', '31-12-2017', '01-01-2018', '02-01-2018', '03-01-2018', '04-01-2018', '05-01-2018', '06-01-2018', '07-01-2018', '08-01-2018', '09-01-2018'], dtype='<U10') ``` **Also, what will be the shape of `data_t`?** Code ``` python= data_t.shape ``` > **Output** ``` (6, 96) ``` #### Let's extract all the columns and save them in seperate variables. Code ``` python= date, step_count, mood, calories_burned, hours_of_sleep, activity_status = data.T step_count ``` > **Output** ``` array(['5464', '6041', '25', '5461', '6915', '4545', '4340', '1230', '61', '1258', '3148', '4687', '4732', '3519', '1580', '2822', '181', '3158', '4383', '3881', '4037', '202', '292', '330', '2209', '4550', '4435', '4779', '1831', '2255', '539', '5464', '6041', '4068', '4683', '4033', '6314', '614', '3149', '4005', '4880', '4136', '705', '570', '269', '4275', '5999', '4421', '6930', '5195', '546', '493', '995', '1163', '6676', '3608', '774', '1421', '4064', '2725', '5934', '1867', '3721', '2374', '2909', '1648', '799', '7102', '3941', '7422', '437', '1231', '1696', '4921', '221', '6500', '3575', '4061', '651', '753', '518', '5537', '4108', '5376', '3066', '177', '36', '299', '1447', '2599', '702', '133', '153', '500', '2127', '2203'], dtype='<U10') ``` Code ``` python= step_count.dtype ``` > **Output** ``` dtype('<U10') ``` Notice the data type of step_count and other variables. It's a string type where **U** means Unicode String and 10 means 10 bytes. **Why? Because Numpy type-casted all the data to strings.** #### Let's convert the data types of these variables. **Step Count** Code ``` python= step_count = np.array(step_count, dtype = 'int') step_count.dtype ``` > **Output** ``` dtype('int64') ``` Code ``` python= step_count ``` > **Output** ``` array([5464, 6041, 25, 5461, 6915, 4545, 4340, 1230, 61, 1258, 3148, 4687, 4732, 3519, 1580, 2822, 181, 3158, 4383, 3881, 4037, 202, 292, 330, 2209, 4550, 4435, 4779, 1831, 2255, 539, 5464, 6041, 4068, 4683, 4033, 6314, 614, 3149, 4005, 4880, 4136, 705, 570, 269, 4275, 5999, 4421, 6930, 5195, 546, 493, 995, 1163, 6676, 3608, 774, 1421, 4064, 2725, 5934, 1867, 3721, 2374, 2909, 1648, 799, 7102, 3941, 7422, 437, 1231, 1696, 4921, 221, 6500, 3575, 4061, 651, 753, 518, 5537, 4108, 5376, 3066, 177, 36, 299, 1447, 2599, 702, 133, 153, 500, 2127, 2203]) ``` **What will be shape of this array?** Code ``` python= step_count.shape ``` > **Output** ``` (96,) ``` * We saw in last class that since it is a 1D array, its shape will be `(96, )`. * If it were a 2D array, its shape would've been `(96, 1)`. **Calories Burned** Code ``` python= calories_burned = np.array(calories_burned, dtype = 'int') calories_burned.dtype ``` > **Output** ``` dtype('int64') ``` **Hours of Sleep** Code ``` python= hours_of_sleep = np.array(hours_of_sleep, dtype = 'int') hours_of_sleep.dtype ``` > **Output** ``` dtype('int64') ``` **Mood** `Mood` belongs to categorical data type. As the name suggests, categorical data type has two or more categories in it. Let's check the values of `mood` variable - Code ``` python= mood ``` > **Output** ``` array(['Neutral', 'Sad', 'Sad', 'Sad', 'Neutral', 'Sad', 'Sad', 'Sad', 'Sad', 'Sad', 'Sad', 'Sad', 'Happy', 'Sad', 'Sad', 'Sad', 'Sad', 'Neutral', 'Neutral', 'Neutral', 'Neutral', 'Neutral', 'Neutral', 'Happy', 'Neutral', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Neutral', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Neutral', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Neutral', 'Sad', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Happy', 'Sad', 'Neutral', 'Neutral', 'Sad', 'Sad', 'Neutral', 'Neutral', 'Happy', 'Neutral', 'Neutral', 'Sad', 'Neutral', 'Sad', 'Neutral', 'Neutral', 'Sad', 'Sad', 'Sad', 'Sad', 'Happy', 'Neutral', 'Happy', 'Neutral', 'Sad', 'Sad', 'Sad', 'Neutral', 'Neutral', 'Sad', 'Sad', 'Happy', 'Neutral', 'Neutral', 'Happy'], dtype='<U10') ``` Code ``` python= np.unique(mood) ``` > **Output** ``` array(['Happy', 'Neutral', 'Sad'], dtype='<U10') ``` **Activity Status** Code ``` python= activity_status ``` > **Output** ``` array(['Inactive', 'Inactive', 'Inactive', 'Inactive', 'Active', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Active', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Active', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Active', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Active', 'Active', 'Active', 'Active', 'Active', 'Active', 'Active', 'Active', 'Active', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Active', 'Active', 'Active', 'Active', 'Active', 'Active', 'Active', 'Active', 'Active', 'Active', 'Active', 'Active', 'Inactive', 'Active', 'Active', 'Inactive', 'Active', 'Active', 'Active', 'Active', 'Active', 'Inactive', 'Active', 'Active', 'Active', 'Active', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Active', 'Active', 'Active', 'Active', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Inactive', 'Active', 'Inactive', 'Active'], dtype='<U10') ``` Since we've extracted form the same source array, we know that - `mood[0]` and `step_count[0]` - There is a connection between them, as they belong to the same record. Also, we know that their length will be the same, i.e. `96` Now let's look at something really interesting. \ **Can we extract the step counts, when the mood was Happy?** Code ``` python= step_count_happy = step_count[mood == 'Happy'] len(step_count_happy) ``` > **Output** ``` 40 ``` Let's also find for when mood was Sad. ``` python= step_count_sad = step_count[mood == 'Sad'] len(step_count_sad) ``` > **Output** ``` 29 ``` Let's also find for when mood was Neutral. ``` python= step_count_neutral = step_count[mood == 'Neutral'] len(step_count_neutral) ``` > **Output** ``` 27 ``` \ **How can we collect data for when mood was either happy or neutral?** Code ``` python= step_count_happy_or_neutral = step_count[(mood == 'Neutral') | (mood == 'Happy')] len(step_count_happy_or_neutral) ``` > **Output** ``` 67 ``` \ **Let's try to compare step counts on bad mood days and good mood days.** Code ``` python= # Average step count on Sad mood days - np.mean(step_count_sad) ``` > **Output** ``` 2103.0689655172414 ``` Code ``` python= # Average step count on Happy days - np.mean(step_count_happy) ``` > **Output** ``` 3392.725 ``` Code ``` python= # Average step count on Neutral days - np.mean(step_count_neutral) ``` > **Output** ``` 3153.777777777778 ``` As you can see, this data tells us a lot about user behaviour. This way we can analyze data and learn. This is just the second class on numpy, we will learn many more concepts related to this, and pandas also. \ **Let's try to check the mood when step count was greater/lesser.** Code ``` python= # mood when step count > 4000 np.unique(mood[step_count > 4000], return_counts = True) ``` > **Output** ``` (array(['Happy', 'Neutral', 'Sad'], dtype='<U10'), array([22, 9, 7])) ``` Out of 38 days when step count was more than 4000, user was feeling happy on 22 days. Code ``` python= # mood when step count <= 2000 np.unique(mood[step_count <= 2000], return_counts = True) ``` > **Output** ``` (array(['Happy', 'Neutral', 'Sad'], dtype='<U10'), array([13, 8, 18])) ``` Out of 39 days, when step count was less than 2000, user was feeling sad on 18 days. #### This suggests that there may be a correlation between `Mood` and `Step Count`. --- title: Unlock Assignment & ask learner to solve in live class description: duration: 1800 card_type: cue_card --- * <span style=“color:skyblue”>Unlock the assignment for learners</span> by clicking the **“question mark”** button on the top bar. <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/078/685/original/Screenshot_2024-06-19_at_7.17.12_PM.png?1718804854" width=200 /> * If you face any difficulties using this feature, please refer to this video on how to unlock assignments. * <span style=“color:red”>**Note:** The following video is strictly for instructor reference only. [VIDEO LINK](https://www.loom.com/share/15672134598f4b4c93475beda227fb3d?sid=4fb31191-ae8c-4b18-bf81-468d2ffd9bd4)</span> ### Conducting a Live Assignment Solution Session: 1. Once you unlock the assignments, ask if anyone in the class would like to solve a question live by sharing their screen. 2. Select a learner and grant permission by navigating to <span style=“color:skyblue”>**Settings > Admin > Unmuted Audience Can Share**, then select **Audio, Video, and Screen**.</span> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/111/113/original/image.png?1740484517" width=400 /> 3. Allow the selected learner to share their screen and guide them through solving the question live. 4. Engage with both the learner sharing the screen and other students in the class to foster an interactive learning experience. ### Practice Coding Question(s) You can pick the following question and solve it during the lecture itself. This will help the learners to get familiar with the problem solving process and motivate them to solve the assignments. <span style="background-color: pink;">Make sure to start the doubt session before you solve this question.</span> Q. https://www.scaler.com/hire/test/problem/26836/ - Extract sub array

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully