agarwallkanchan29/numpy-array-operations - Jovian
Learn data science and machine learning by building real-world projects on Jovian

Assignment 2 - Numpy Array Operations

This assignment is part of the course "Data Analysis with Python: Zero to Pandas". The objective of this assignment is to develop a solid understanding of Numpy array operations. In this assignment you will:

  1. Pick 5 interesting Numpy array functions by going through the documentation: https://numpy.org/doc/stable/reference/routines.html
  2. Run and modify this Jupyter notebook to illustrate their usage (some explanation and 3 examples for each function). Use your imagination to come up with interesting and unique examples.
  3. Upload this notebook to your Jovian profile using jovian.commit and make a submission here: https://jovian.ml/learn/data-analysis-with-python-zero-to-pandas/assignment/assignment-2-numpy-array-operations
  4. (Optional) Share your notebook online (on Twitter, LinkedIn, Facebook) and on the community forum thread: https://jovian.ml/forum/t/assignment-2-numpy-array-operations-share-your-work/10575 .
  5. (Optional) Check out the notebooks shared by other participants and give feedback & appreciation.

The recommended way to run this notebook is to click the "Run" button at the top of this page, and select "Run on Binder". This will run the notebook on mybinder.org, a free online service for running Jupyter notebooks.

Try to give your notebook a catchy title & subtitle e.g. "All about Numpy array operations", "5 Numpy functions you didn't know you needed", "A beginner's guide to broadcasting in Numpy", "Interesting ways to create Numpy arrays", "Trigonometic functions in Numpy", "How to use Python for Linear Algebra" etc.

NOTE: Remove this block of explanation text before submitting or sharing your notebook online - to make it more presentable.

exciting numpy functions

Intro to my fav 5

Following are the five Numpy and list functions.

  • geomspace()
  • flatten()
  • binary_repr()
  • rsplit()
  • busday_count()

The recommended way to run this notebook is to click the "Run" button at the top of this page, and select "Run on Binder". This will run the notebook on mybinder.org, a free online service for running Jupyter notebooks.

!pip install jovian --upgrade -q
import jovian
jovian.commit(project='numpy-array-operations')
[jovian] Updating notebook "agarwallkanchan29/numpy-array-operations" on https://jovian.ai [jovian] Committed successfully! https://jovian.ai/agarwallkanchan29/numpy-array-operations

Let's begin by importing Numpy and listing out the functions covered in this notebook.

import numpy as np
# List of functions explained 
# function1 = np.geomspace(start,stop)
# function2 = ndarray.flatten()
# function3 = n.binary_repr()
# function4 = str.rsplit()
# function5 = day.busday_count()

Function 1 - np.geomspace (start,stop,no.ofvalues)

This is function to generate a geometric progression type of sequence provided that the following are provided: start = The lowerbound value of the sequence(included in the sequence). stop = The upperbound of the sequence(inclued in the sequence). no. of values = The total number of values required in the sequence. start AND stop are MANDATORY arguments. no. of values is NOT MANDATORY and its DEFAULT value is 50.

# Example 1 - 
arr1 = np.geomspace(2,144)
arr1
array([  2.        ,   2.18240195,   2.38143913,   2.5986287 ,
         2.83562616,   3.09423803,   3.37643555,   3.68436976,
         4.02038787,   4.38705116,   4.7871545 ,   5.22374765,
         5.70015852,   6.22001853,   6.78729027,   7.40629776,
         8.08175932,   8.81882364,   9.62310894,  10.50074585,
        11.4584241 ,  12.50344353,  13.64376975,  14.88809484,
        16.24590358,  17.72754581,  19.34431525,  21.10853563,
        23.03365463,  25.13434636,  27.42662323,  29.92795797,
        32.65741687,  35.63580509,  38.88582521,  42.43225033,
        46.30211288,  50.52491065,  55.1328317 ,  60.16099963,
        65.64774137,  71.6348793 ,  78.16805004,  85.29705232,
        93.07622654, 101.56486902, 110.82768397, 120.93527665,
       131.96469163, 144.        ])

Explanation : START STOP arguments are given but no. value required are not given.Thus the system automatically sets it to 50.

# Example 2 - working
arr1 = np.geomspace(2,128,7)
arr1
array([  2.,   4.,   8.,  16.,  32.,  64., 128.])

Explanation : In this example within the same range number of values required in the sequence is defined to be 7.Thus, a sequence consisting of 7 values in a GP format is format

# Example 3 - breaking (to illustrate when it breaks)
arr1 = np.geomspace(1,-128.0,7)
arr1
/opt/conda/lib/python3.9/site-packages/numpy/core/function_base.py:424: RuntimeWarning: invalid value encountered in log10 log_stop = _nx.log10(stop)
array([   1.,   nan,   nan,   nan,   nan,   nan, -128.])

Explanation: Thought all the three arguments are given but the function does not work because the geometric series changes from a positive to negative value which cannot be handled by the function. You can either make a completely positive sequence or a completely negative sequence.

Some closing comments about when to use this function.

jovian.commit()
[jovian] Updating notebook "agarwallkanchan29/numpy-array-operations" on https://jovian.ai [jovian] Committed successfully! https://jovian.ai/agarwallkanchan29/numpy-array-operations

flatten

This a function that converts an n-dimensional array into a 1-dimensional array,i.e., flattens the array into 1-D.

# Example 1 - working
arr=np.array([[1,2,3],[4,5,6],[7,8,9]])
print ('Original array:\n',arr)
arr=arr.flatten()
print ('After flattening :\n',arr)
Original array: [[1 2 3] [4 5 6] [7 8 9]] After flattening : [1 2 3 4 5 6 7 8 9]

Explanation : This is a simple example to understand the working of flatten function .

# Example 2 - working
arr=np.array([[[1,2,3],[4,5,6],[7,8,9]],[[1,2,3],[4,5,6],[7,8,9]],[[1,2,3],[4,5,6],[7,8,9]]])
print ('Original array:\n',arr)
arr=arr.flatten()
print ('After flattening :\n',arr)
Original array: [[[1 2 3] [4 5 6] [7 8 9]] [[1 2 3] [4 5 6] [7 8 9]] [[1 2 3] [4 5 6] [7 8 9]]] After flattening : [1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9]

Explanation : This example shows the flattening of a 3-D array,likewise,we can flatten a array of higher order also.

# Example 3 - breaking (to illustrate when it breaks)
arr=np.array([[1,2,3],[4,5,6],[7,8,9,10]])
print ('Original array:\n',arr)
arr=arr.flatten()
print ('After flattening :\n',arr)
Original array: [list([1, 2, 3]) list([4, 5, 6]) list([7, 8, 9, 10])] After flattening : [list([1, 2, 3]) list([4, 5, 6]) list([7, 8, 9, 10])]
/tmp/ipykernel_35/67848690.py:2: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray. arr=np.array([[1,2,3],[4,5,6],[7,8,9,10]])

Explanation : This example shows that a highly directional array is reuired otherwise it is considered as list and cannot be flattened.

Some closing comments about when to use this function.

jovian.commit()
[jovian] Updating notebook "agarwallkanchan29/numpy-array-operations" on https://jovian.ai [jovian] Committed successfully! https://jovian.ai/agarwallkanchan29/numpy-array-operations

binary_repr

This function returns the binary representation of the input number as a string.

# Example 1 - working
n=3
print(np.binary_repr(n))
11

Explanation : This is a basic example to understand the working of the function

# Example 2 - working
n=-3
print(np.binary_repr(n))
-11

Explanation : For negative numbers, if width is not given, a minus sign is added to the front. If width is given, the two’s complement of the number is returned, with respect to that width.

# Example 3 - breaking (to illustrate when it breaks)
np.binary_repr(6.7)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_35/109885427.py in <module> 1 # Example 3 - breaking (to illustrate when it breaks) ----> 2 np.binary_repr(6.7) /opt/conda/lib/python3.9/site-packages/numpy/core/numeric.py in binary_repr(num, width) 2018 # Ensure that num is a Python integer to avoid overflow or unwanted 2019 # casts to floating point. -> 2020 num = operator.index(num) 2021 2022 if num == 0: TypeError: 'float' object cannot be interpreted as an integer

Explanation : You cannot find the binary representation of a floating value.

Some closing comments about when to use this function.

jovian.commit()
[jovian] Updating notebook "agarwallkanchan29/numpy-array-operations" on https://jovian.ai [jovian] Committed successfully! https://jovian.ai/agarwallkanchan29/numpy-array-operations

char.rsplit(a, sep=None, maxsplit=None)

For each element in a, return a list of the words in the string, using sep as the delimiter string. a : array_like of string sep : str or unicode, (optional).If sep is not specified or None, any whitespace string is a separator. maxsplit : int, (optional). If maxsplit is given, at most maxsplit splits are done, the rightmost ones.

# Example 1 - working
s='my name is kanchan'
str.rsplit(s)
['my', 'name', 'is', 'kanchan']

Explanation : This is an example to understand the basic functionality of the function.

# Example 2 - working
s='orange,mango,grapes,banana'
str.rsplit(s,sep=',')
['orange', 'mango', 'grapes', 'banana']

Explanation : Here we can understand the use of sep parameter passed to the function .

# Example 3 - breaking (to illustrate when it breaks)
s='my name is : kanchan and I like orange,mango,grapes,banana'
str.rsplit(s)
['my',
 'name',
 'is',
 ':',
 'kanchan',
 'and',
 'I',
 'like',
 'orange,mango,grapes,banana']

Explanation a: Though the function runs but it gives an inappropriate result because the sentence given as input compromise of separation of type white space as well as comma.The function cannot identify these kind of conditions.

Some closing comments about when to use this function.

jovian.commit()
[jovian] Updating notebook "agarwallkanchan29/numpy-array-operations" on https://jovian.ai [jovian] Committed successfully! https://jovian.ai/agarwallkanchan29/numpy-array-operations

busday_count(begindates, enddates, weekmask='1111100', holidays=[])

Counts the number of valid days between begindates and enddates, not including the day of enddates. If enddates specifies a date value that is earlier than the corresponding begindates date value, the count will be negative.

  1. begindates : The array of the first dates for counting.
  2. enddates : The array of the end dates for counting, which are excluded from the count themselves.
  3. weekmask : str (optional) A seven-element array indicating which of Monday through Sunday are valid days. Like [1,1,1,1,1,0,0]; ‘1111100’; or “Mon Tue Wed Thu Fri”, made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun
  4. holidays : (optional) An array of dates to consider as invalid dates. They may be specified in any order. Returns out array of int. An array with a shape from broadcasting begindates and enddates together, containing the number of valid days between the begin and end dates.
# Example 1 - working
np.busday_count('2021','2022')
261

Explanation : This is an example to understand the basic functionality of the function.By default saturdays and sundays are not considered as week days and thus, they are excluded.

# Example 2 - working
np.busday_count('2021','2022',weekmask='1111000')
208

Explanation : This is an example to understand the use of the weekmask parameter .

# Example 3 - breaking (to illustrate when it breaks)
np.busday_count('2022','2021',weekmask='1111000')
-208

Explanation : Though the function runs but it gives an inappropriate result because the input compromise of end date which occurs before the begin data.So, the function the function returns this kind of negative output.

Some closing comments about when to use this function.

jovian.commit()
[jovian] Updating notebook "agarwallkanchan29/numpy-array-operations" on https://jovian.ai [jovian] Committed successfully! https://jovian.ai/agarwallkanchan29/numpy-array-operations

can_cast(from_, to, casting='safe')

Returns True if cast between data types can occur according to the casting rule.

  1. from_ : Data type, scalar, or array to cast from. 2)to : Data type to cast to.
  2. casting : {‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, (optional) Controls what kind of data casting may occur. ‘no’ means the data types should not be cast at all. ‘equiv’ means only byte-order changes are allowed. ‘safe’ means only casts which can preserve values are allowed. ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed. ‘unsafe’ means any data conversions may be done. Returns bool. True if cast can occur according to the casting rule.
# Example 1 - working
np.can_cast(int,str)
True

Explanation : This is an example to understand the basic functionality of the function.

# Example 2 - working
np.can_cast(float,complex)
True

Explanation : Casting between a simple data type and a structured one is possible only for “unsafe” casting.

# Example 3 - breaking (to illustrate when it breaks)
np.can_cast('<i8', '>u4', same_kind)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) /tmp/ipykernel_35/3526777729.py in <module> 1 # Example 3 - breaking (to illustrate when it breaks) ----> 2 np.can_cast('<i8', '>u4', same_kind) NameError: name 'same_kind' is not defined

Explanation : The function gives an error because the input requires last parameter of type str.So, the function returns this kind of error.

Some closing comments about when to use this function.

jovian.commit()

Conclusion

Following are the five Numpy and list functions covered : geomspace() flatten() binary_repr() rsplit() busday_count()

BONUS FUNCTION : can_cast()

Reference Links

Provide links to your references and other interesting articles about Numpy arrays:

jovian.commit()
[jovian] Attempting to save notebook.. [jovian] Updating notebook "aakashns/numpy-array-operations" on https://jovian.ml/ [jovian] Uploading notebook.. [jovian] Capturing environment.. [jovian] Committed successfully! https://jovian.ml/aakashns/numpy-array-operations