Python W3school
Python W3school
x, y, z = "Orange","Banana",123 x = y = z = "Orange"
List operation
Change a range of item values
L = ["apple","banana","cherry","orange","kiwi"]
# ['apple', 'blackcurrent', 'watermelon', 'orange', 'kiwi']
L[1:3] = ["blackcurrent","watermelon"]
Insert item
L.insert(1,"melon") # ['apple', 'melon', 'blackcurrent', 'watermelon', 'orange', 'kiwi']
Extend List
L2 = ["mango","pineapple","papaya"]
# ['apple', 'banana', 'cherry', 'orange', 'kiwi', 'mango', 'pineapple', 'papaya']
L.extend(L2)
You can add any iterable object(tuples,sets,dictionaries)
T = ("kiwi","orange")
# ['apple', 'banana', 'cherry', 'orange', 'kiwi', 'mango', 'pineapple', 'papaya', 'kiwi', 'orange']
L.extend(T)
Remove specified item
# ['apple', 'cherry', 'orange', 'kiwi', 'mango', 'pineapple', 'papaya', 'kiwi', 'orange']
L.remove("banana")
Remove specified index
# ['apple', 'orange', 'kiwi', 'mango', 'pineapple', 'papaya', 'kiwi', 'orange']
L.pop(1) is equal to del L[1]
Clear the list
L.clear() # []
Sort Method
L.sort() # Ascending
L.sort(reverse = True) # Descending
By using the keyword argument key=function, the function will return a number that will be used to sort the
list (the lowest number first. Example, sort the list based on how close the number is to 50.
def my_function(n):
return abs(n-50)
L = [100,50,65,82,23]
# [50, 65, 23, 82, 100]
L.sort(key = my_function)
Reverse order
What if you want to reverse the order of a list, regardless of the alphabet?
L = ["banana","orange","kiwi","cherry"]
# ['cherry', 'kiwi', 'orange', 'banana']
L.reverse()
Copy List
You can not copy a list simply by typing List2 = List1, because: List2 will only be a reference to List1, and
changes made in List1 will automatically also be made in List2.
We can solve it by choosing one from two way:-
# First Way
List1 = ["apple","banana","cherry"]
List2 = List1.copy()
# Second Way
List2 = list(List1)
Get Items receive a tuple of arguments and can access the items
for k in X: print(X[k]) if you don’t know how many keyword arguments that will
# second way be passed into your function, add two ** before the
for v in X.values(): print(v) parameter name in the function definition. This way the
function will receive a dictionary of arguments, and can
# print key with value
access the items accordingly
for k,v in X.items(): print(k,v)
def my_func(**kid):
copy a Dictionary
print("His Last name is " + kid["lname"])
y = d.copy() # OR
# the youngest child is Linus
y = dict(d)
my_func(fname = "Tobias",lname = "Refsnes")
Python Lambda
A lambda function is a small anonymous function. A lambda function can take any number of arguments,
but can only have one expression. lambda arguments : expression
x = lambda a : a + 10 print(x(5)) # 15
Lambda functions can take any number of arguments:
x = lambda a, b : a * b print(x(5, 6))
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous function inside another
function. Use lambda functions when an anonymous function is required for a short period of time. Say
you have a function definition that takes one argument, and that argument will be multiplied with an
unknown number: Use that function definition to make a function that always doubles the number you
send in:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Or, use the same function definition to make a function that always triples the number you send in:
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Or, use the same function definition to make both functions, in the same program:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Create a Class class Person:
def __init__(self, name, age):
self.name = name
To create a class, use the keyword class:
self.age = age
class MyClass:
def myfunc(self):
x=5
print("Hello my name is " + self.name)
Create Object
p1 = Person("John", 36)
Now we can use the class named MyClass to
p1.myfunc()
create objects:
It does not have to be named self , you can call it
p1 = MyClass() print(p1.x)
whatever you like, but it has to be the first parameter
The __init__() Function of any function in the class:
To understand the meaning of classes we have Use the words mysillyobject and abc instead of self:
to understand the built-in __init__() function. All class Person:
classes have a function called __init__(), which is def __init__(mysillyobject, name, age):
always executed when the class is being
mysillyobject.name = name
initiated. Use the __init__() function to assign
values to object properties, or other operations mysillyobject.age = age
that are necessary to do when the object is def myfunc(abc):
being created:
print("Hello my name is " + abc.name)
class Person:
p1 = Person("John", 36)
def __init__(self, name, age):
p1.myfunc()
self.name = name
Modify Object Properties
self.age = age
You can modify properties on objects like this:
p1 = Person("John", 36)
p1.age = 40
print(p1.name)
Delete Object Properties
The self Parameter
You can delete properties on objects by using
The self parameter is a reference to the current
instance of the class, and is used to access the del keyword:
variables that belongs to the class. del p1.age
Object Methods
Delete Objects
Methods in objects are functions that belong to
You can delete objects by using the del keyword:
the object.
del p1
Python Inheritance Now the Student class has the same properties and
Inheritance allows us to define a class that methods as the Person class.
inherits all the methods and properties from x = Student("Mike", "Olsen")
x.printname()
another class.
Add the __init__() Function
Parent class is the class being inherited from,
So far we have created a child class that inherits the
also called base class.
properties and methods from its parent.
Child class is the class that inherits from
We want to add the __init__() function to the child
another class, also called derived class.
class (instead of the pass keyword).
class Student(Person):
Create a Parent Class
def __init__(self, fname, lname):
class Person:
#add properties etc.
def __init__(self, fname, lname):
When you add the __init__() function, the child class
self.firstname = fname
will no longer inherit the parent's __init__() function.
self.lastname = lname
def printname(self):
Note:
print(self.firstname, self.lastname)
The child's __init__() function overrides the
#Use the Person class to create an object, and
inheritance of the parent's __init__() function.
then execute the printname method:
To keep the inheritance of the
x = Person("John", "Doe")
parent's __init__() function, add a call to the
x.printname()
parent's __init__() function:
class Student(Person):
Create a Child Class
def __init__(self, fname, lname):
To create a class that inherits the functionality
Person.__init__(self, fname, lname)
from another class, send the parent class as a
Now we have successfully added the __init__()
parameter when creating the child class:
function, and kept the inheritance of the parent class,
class Student(Person):
and we are ready to add functionality in
pass
the __init__() function.
Use the super() Function To do so, add another parameter in the __init__()
Python also has a super() function that will function:
make the child class inherit all the methods and class Student(Person):
properties from its parent: def __init__(self, fname, lname, year):
class Student(Person): super().__init__(fname, lname)
def __init__(self, fname, lname):
self.graduationyear = year
super().__init__(fname, lname)
x = Student("Mike", "Olsen", 2019)
By using the super() function, you do not have
to use the name of the parent element, it will
Add Methods
automatically inherit the methods and
class Student(Person):
properties from its parent.
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
Add Properties
self.graduationyear = year
class Student(Person):
def welcome(self):
def __init__(self, fname, lname):
print("Welcome", self.firstname, self.lastname, "to
super().__init__(fname, lname)
the class of", self.graduationyear)
self.graduationyear = 2019
If you add a method in the child class with the same
In the example below, the year 2019 should be
name as a function in the parent class, the inheritance
a variable, and passed into the Student class
of the parent method will be overridden.
when creating student objects.
Python Iterators
An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the
methods __iter__() and __next__().
# the result is a Python dictionary: Use the indent parameter to define the numbers of
print(y["age"]) indents: json.dumps(x, indent=4)
Convert from Python to JSON You can also define the separators, default value is (",
If you have a Python object, you can convert it ", ": "), which means using a comma and a space to
into a JSON string by using separate each object, and a colon and a space to
the json.dumps() method. separate keys from values: Use
import json the separators parameter to change the default
# a Python object (dict):
separator:
x = { "name": "John", "age": 30, "city": "New York"}
json.dumps(x, indent=4, separators=(". ", " = "))
# convert into JSON:
Order the Result
y = json.dumps(x)
The json.dumps() method has parameters to order
# the result is a JSON string:
the keys in the result: Use the sort_keys parameter to
print(y)
specify if the result should be sorted or not:
json.dumps(x, indent=4, sort_keys=True)
RegEx Module Metacharacters
Python has a built-in package called re, which Metacharacters are characters with a special meaning:
can be used to work with Regular Expressions.
Charact Description Example
Import the re module:
er
import re
[] A set of characters "[a-m]"
Example
Search the string to see if it starts with "The" \ Signals a special "\d"
and ends with "Spain" sequence (can also be
import re
txt = "The rain in Spain"
used to escape special
x = re.search("^The.*Spain$", txt)
characters)
RegEx Functions
The re module offers a set of functions that . Any character (except "he..o"
allows us to search a string for a match: newline character)
split Returns a list where the string has {} Exactly the specified "he.{2}o"
been split at each match number of occurrences
Sets
A set is a set of characters inside a pair of square brackets [] with a special meaning:
Set Description
[arn] Returns a match where one of the specified characters (a, r, or n) are present
[a-n] Returns a match for any lower case character, alphabetically between a and n
[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present
[a-zA-Z] Returns a match for any character alphabetically between a and z, lower case OR
upper case
[+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for
any + character in the string
Print the position (start- and end-position) of Print the part of the string where there was a match.
the first match occurrence. The regular expression looks for any words that starts
The regular expression looks for any words that with an upper case "S":
starts with an upper case "S": import re
import re txt = "The rain in Spain"
txt = "The rain in Spain" x = re.search(r"\bS\w+", txt)
x = re.search(r"\bS\w+", txt) print(x.group())
print(x.span()) Note: If there is no match, the value None will be
Print the string passed into the function: returned, instead of the Match Object.
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.string)
Python Try Except try:
The try block lets you test a block of code for print(x)
errors. except:
The except block lets you handle the error. print("An exception occurred")
The else block lets you execute code when Many Exceptions
there is no error. You can define as many exception blocks as you want,
The finally block lets you execute code, e.g. if you want to execute a special block of code for
regardless of the result of the try- and except a special kind of error:
blocks. Print one message if the try block raises
Exception Handling a NameError and another for other errors:
When an error occurs, or exception as we call it, try:
Python will normally stop and generate an error print(x)
message. These exceptions can be handled except NameError:
using the try statement: print("Variable x is not defined")
The try block will generate an exception, except:
because x is not defined: print("Something else went wrong")
Else This can be useful to close objects and clean up
You can use the else keyword to define a block resources:
of code to be executed if no errors were raised: Try to open and write to a file that is not writable:
In this example, the try block does not generate try:
any error: f = open("demofile.txt")
try: try:
print("Hello") f.write("Lorum Ipsum")
except: except:
print("Something went wrong") print("Something went wrong when writing to the
else: file")
print("Nothing went wrong") finally:
Finally f.close()
The finally block, if specified, will be executed except:
regardless if the try block raises an error or not.
try:
print("Something went wrong when opening the
print(x)
file")
except:
The program can continue, without leaving the file
print("Something went wrong")
object open.
finally:
print("The 'try except' is finished")
Raise an exception
As a Python developer you can choose to throw The raise keyword is used to raise an exception.
an exception if a condition occurs. To throw (or You can define what kind of error to raise, and the
raise) an exception, use the raise keyword. text to print to the user.
Raise an error and stop the program if x is Raise a TypeError if x is not an integer:
What is NumPy?
It also has functions for working in domain of Dimensions in Arrays
linear algebra, fourier transform, and matrices. A dimension in arrays is one level of array depth
NumPy stands for Numerical Python. (nested arrays).
Why Use NumPy? 0-D Arrays
In Python we have lists that serve the purpose 0-D arrays, or Scalars, are the elements in an array.
of arrays, but they are slow to process. Each value in an array is a 0-D array.
NumPy aims to provide an array object that is import numpy as np
up to 50x faster than traditional Python lists. arr = np.array(42)
NumPy arrays are stored at one continuous
print(arr)
place in memory unlike lists.
The array object in NumPy is called ndarray, it 1-D Arrays
provides a lot of supporting functions that
An array that has 0-D arrays as its elements is called
make working with ndarray very easy.
uni-dimensional or 1-D array.
Installation of NumPy These are the most common and basic arrays.
!pip install numpy
import numpy as np
NumPy as np arr = np.array([1, 2, 3, 4, 5])
print(arr)
NumPy is usually imported under the np alias.
import numpy as np
2-D Arrays
Checking NumPy Version
An array that has 1-D arrays as its elements is called a
The version string is stored under
2-D array.
__version__ attribute.
import numpy as np These are often used to represent matrix or 2nd order
print(np.__version__) tensors.
NumPy has a whole sub module dedicated
Create a NumPy ndarray Object towards matrix operations called numpy.mat
NumPy is used to work with arrays. The array import numpy as np
object in NumPy is called ndarray. arr = np.array([[1, 2, 3], [4, 5, 6]])
We can create a NumPy ndarray object by using print(arr)
the array() function.
To create an ndarray, we can pass a list, tuple or 3-D arrays
any array-like object into the array() method,
An array that has 2-D arrays (matrices) as its elements
and it will be converted into an ndarray:
is called 3-D array.
import numpy as np
These are often used to represent a 3rd order tensor.
arr = np.array([1, 2, 3, 4, 5])
print(arr)
import numpy as np
print(type(arr)) arr = np.array([[[1, 2, 3], [4, 5, 6]],
import numpy as np [[1, 2, 3], [4, 5, 6]]])
arr = np.array((1, 2, 3, 4, 5)) print(arr)
print(arr)
Check Number of Dimensions? Access 2-D Arrays
NumPy Arrays provides the ndim attribute that To access elements from 2-D arrays we can use
returns an integer that tells us how many comma separated integers representing the
dimensions the array have. dimension and the index of the element.
import numpy as np Think of 2-D arrays like a table with rows and
a = np.array(42) columns, where the row represents the dimension
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
and the index represents the column.
import numpy as np
d = np.array([[[1, 2, 3], [4, 5, 6]],
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
[[1, 2, 3], [4, 5, 6]]])
print('2nd element on 1st row: ', arr[0, 1])
print(a.ndim)
print(b.ndim) Access 3-D Arrays
print(c.ndim)
To access elements from 3-D arrays we can use
print(d.ndim)
comma separated integers representing the
Higher Dimensional Arrays dimensions and the index of the element.
import numpy as np
An array can have any number of dimensions. arr = np.array([[[1, 2, 3], [4, 5, 6]],
When the array is created, you can define the [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])
number of dimensions by using
the ndmin argument. Example Explained
import numpy as np arr[0, 1, 2] prints the value 6.
arr = np.array([1, 2, 3, 4], ndmin=5) And this is why:
The first number represents the first dimension, which
print(arr)
contains two arrays:
print('number of dimensions :',
arr.ndim) [[1, 2, 3], [4, 5, 6]]
and:
In this array the innermost dimension (5th dim) [[7, 8, 9], [10, 11, 12]]
has 4 elements, the 4th dim has 1 element that Since we selected 0, we are left with the first array:
is the vector, the 3rd dim has 1 element that is [[1, 2, 3], [4, 5, 6]]
the matrix with the vector, the 2nd dim has 1 The second number represents the second
element that is 3D array and 1st dim has 1 dimension, which also contains two arrays:
element that is a 4D array. [1, 2, 3]
and:
Access Array Elements [4, 5, 6]
Since we selected 1, we are left with the second array:
Array indexing is the same as accessing an
[4, 5, 6]
array element.
You can access an array element by The third number represents the third dimension,
referring to its index number. which contains three values:
The indexes in NumPy arrays start with 0, 4
meaning that the first element has index 0, 5
and the second has index 1 etc. 6
import numpy as np
Since we selected 2, we end up with the third value:
arr = np.array([1, 2, 3, 4])
print(arr[0]) 6
np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12]) import numpy as np
newarr = arr.reshape(2, 3, 2) arr = np.array([[1, 2, 3], [4, 5, 6]])
print(newarr) newarr = arr.reshape(-1)
# [[[ 1 2] print(newarr)
[ 3 4] Note: There are a lot of functions for changing
[ 5 6]] the shapes of arrays in
[[ 7 8] numpy flatten, ravel and also for rearranging
[ 9 10] the elements rot90, flip, fliplr, flipud etc.
[11 12]]]
Iterating Arrays Using nditer() Iterating With Different Step Size
The function nditer() is a helping function We can use filtering and followed by iteration.
that can be used from very basic to very Iterate through every scalar element of the 2D
advanced iterations. It solves some basic array skipping 1 element:
issues which we face in iteration, lets go import numpy as np
through it with examples. arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
Iterating on Each Scalar Element
for x in np.nditer(arr[:, ::2]):
In basic for loops, iterating through each
print(x)
scalar of an array we need to
use n for loops which can be difficult to # 1
write for arrays with very high 3
dimensionality.
import numpy as np 5
arr = np.array([[[1, 2], [3, 4]], 7
[[5, 6], [7, 8]]]) Enumerated Iteration Using ndenumerate()
for x in np.nditer(arr): Enumeration means mentioning sequence
print(x) number of somethings one by one.
Sometimes we require corresponding index of
# 1 the element while iterating,
2 the ndenumerate() method can be used for
those usecases.
3
import numpy as np
4
arr = np.array([1, 2, 3])
5
for idx, x in np.ndenumerate(arr):
6
print(idx, x)
7
# (0,) 1
8
(1,) 2
Iterating Array With Different Data Types
(2,) 3
We can use op_dtypes argument and pass Enumerate on following 2D array's elements:
it the expected datatype to change the
datatype of elements while iterating. import numpy as np
NumPy does not change the data type of arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
the element in-place (where the element is
in array) so it needs some other space to for idx, x in np.ndenumerate(arr):
perform this action, that extra space is print(idx, x)
called buffer, and in order to enable it
# (0, 0) 1
in nditer() we pass flags=['buffered'].
import numpy as np (0, 1) 2
arr = np.array([1, 2, 3])
(0, 2) 3
for x in np.nditer(arr,
flags=['buffered'], op_dtypes=['S']): (0, 3) 4
print(x)
…………
array into three 2-D arrays along rows. print(x) # (array([3, 5, 6]),)
import numpy as np Find the indexes where the values are even:
[7, 8, 9], [10, 11, 12], [13, 14, 15], arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
Note: Similar alternates To search for more than one value, use an array
with the specified values.
to vstack() and dstack() are available import numpy as np
as vsplit() and dsplit(). arr = np.array([1, 3, 5, 7])
Searching Arrays x = np.searchsorted(arr, [2, 4, 6])
Sorting a 2-D Array Create a filter array that will return only values
Generate a 2-D array with 3 rows, each Probability Density Function: A function that
row containing 5 random numbers: describes a continuous probability. i.e.
from numpy import random probability of all values in an array.
x = random.rand(3, 5)
print(x) We can generate random numbers based on
defined probabilities using the choice() method
Generate Random Number From Array of the random module.
The choice() method allows you to The choice() method allows us to specify the
generate a random value based on an
probability for each value.
array of values.
The choice() method takes an array as a The probability is set by a number between 0
parameter and randomly returns one of the and 1, where 0 means that the value will never
values. occur and 1 means that the value will always
Return one of the values in an array: occur.
from numpy import random
x = random.choice([3, 5, 7, 9]) Generate a 1-D array containing 100 values,
print(x)
where each value has to be 3, 5, 7 or 9.
The choice() method also allows you to The probability for the value to be 3 is set to be
return an array of values. 0.1
Add a size parameter to specify the shape The probability for the value to be 5 is set to be
of the array. 0.3
Generate a 2-D array that consists of the The probability for the value to be 7 is set to be
values in the array parameter (3, 5, 7, and 0.6
9): The probability for the value to be 9 is set to be
from numpy import random
0
x = random.choice([3, 5, 7, 9],
size=(3, 5))
print(x)
Plotting a Distplot
Import Matplotlib import matplotlib.pyplot as plt
Import the pyplot object of the Matplotlib import seaborn as sns
module in your code using the following sns.distplot([0, 1, 2, 3, 4, 5])
statement: plt.show()
import matplotlib.pyplot as plt Plotting a Distplot Without the Histogram
Import Seaborn import matplotlib.pyplot as plt
Binomial Distribution
Binomial Distribution
Binomial Distribution is a Discrete Distribution.
It describes the outcome of binary
scenarios, e.g. toss of a coin, it will either
be head or tails.
It has three parameters:
n - number of trials.
size - The shape of the returned array. The main difference is that normal distribution is
continous whereas binomial is discrete, but if
Discrete Distribution: The distribution is defined
there are enough data points it will be quite
at separate set of events, e.g. a coin toss's
similar to normal distribution with certain loc and
scale.
from numpy import random
result is discrete as it can be only head or
import matplotlib.pyplot as plt
tails whereas height of people is continuous
import seaborn as sns
as it can be 170, 170.1, 170.11 and so on.
sns.distplot(random.normal(loc=50, scale=5,
Given 10 trials for coin toss generate 10
size=1000), hist=False, label='normal')
data points:
sns.distplot(random.binomial(n=100, p=0.5,
from numpy import random
size=1000), hist=False, label='binomial')
x = random.binomial(n=10, p=0.5,
plt.show()
size=10)
print(x)
Visualization of Binomial Distribution
from numpy import random
import matplotlib.pyplot as plt
import seaborn as sns
sns.distplot(random.binomial(n=10,
p=0.5, size=1000), hist=True, kde=False)
plt.show()
a - lower bound - default 0 .0. loc - mean, where the peak is. Default 0.
Multinomial Distribution
size - The shape of the returned array. Chi Square distribution is used as a basis to
verify the hypothesis.
Draw out a sample for exponential
distribution with 2.0 scale with 2x3 size: It has two parameters:
from numpy import random
df - (degree of freedom).
x = random.exponential(scale=2,
size - The shape of the returned array.
size=(2, 3))
print(x) Draw out a sample for chi squared distribution
Visualization of Exponential Distribution with degree of freedom 2 with size 2x3:
from numpy import random from numpy import random
import matplotlib.pyplot as plt x = random.chisquare(df=2, size=(2, 3))
import seaborn as sns print(x)
sns.distplot(random.exponential(size=100 Visualization of Chi Square Distribution
0), hist=False) from numpy import random
plt.show() import matplotlib.pyplot as plt
import seaborn as sns
sns.distplot(random.chisquare(df=1,
size=1000), hist=False)
plt.show()
Rayleigh Distribution Similarity Between Rayleigh and Chi Square
Distribution
Rayleigh distribution is used in signal
processing.
At unit stddev the and 2 degrees of freedom
It has two parameters: rayleigh and chi square represent the same
distributions.
scale - (standard deviation) decides how
flat the distribution will be default 1.0). Pareto Distribution
size - The shape of the returned array. A distribution following Pareto's law i.e. 80-20
distribution (20% factors cause 80% outcome).
Draw out a sample for rayleigh distribution
with scale of 2 with size 2x3: It has two parameter:
from numpy import random
a - shape parameter.
x = random.rayleigh(scale=2,
size - The shape of the returned array.
size=(2, 3))
print(x) Draw out a sample for pareto distribution with
Visualization of Rayleigh Distribution shape of 2 with size 2x3:
from numpy import random from numpy import random
import matplotlib.pyplot as plt x = random.pareto(a=2, size=(2, 3))
import seaborn as sns print(x)
sns.distplot(random.rayleigh(size=1000), Visualization of Pareto Distribution
hist=False) from numpy import random
plt.show() import matplotlib.pyplot as plt
import seaborn as sns
sns.distplot(random.pareto(a=2, size=1000),
kde=False)
plt.show()
Zipf Distribution
Visualization of Zipf Distribution
Co nverting iterative statements into a To create you own ufunc, you have to define a
vector based operation is called function, like you do with normal functions in
vectorization. Python, then you add it to your NumPy ufunc
library with the frompyfunc() method.
It is faster as modern CPUs are optimized
for such operations. The frompyfunc() method takes the following
arguments:
Add the Elements of Two Lists
1. function - the name of the function.
2. inputs - the number of input arguments
list 1: [1, 2, 3, 4] (arrays).
3. outputs - the number of output arrays.
list 2: [4, 5, 6, 7]
Create your own ufunc for addition:
One way of doing it is to iterate over both
import numpy as np
of the lists and then sum each elements.
def myadd(x, y):
Without ufunc, we can use Python's built- return x+y
in zip() method: myadd = np.frompyfunc(myadd, 2, 1)
x = [1, 2, 3, 4] print(myadd([1, 2, 3, 4], [5, 6, 7, 8]))
y = [4, 5, 6, 7] Check if a Function is a ufunc
z = []
for i, j in zip(x, y): Check the type of a function to check if it is a
z.append(i + j) ufunc or not.
Use an if statement to check if the function The subtract() function subtracts the values from
is a ufunc or not: one array with the values from another array,
and return the results in a new array.
import numpy as np
if type(np.add) == np.ufunc: Subtract the values in arr2 from the values in
print('add is ufunc') arr1:
else:
print('add is not ufunc') import numpy as np
arr1 = np.array([10, 20, 30, 40, 50, 60])
Simple Arithmetic arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.subtract(arr1, arr2)
print(newarr)
You could use arithmetic
operators + - * / directly between NumPy The example above will return [-10 -1 8 17 26
arrays, but this section discusses an
35] which is the result of 10-20, 20-21, 30-22
extension of the same where we have
functions that can take any array-like etc.
objects e.g. lists, tuples etc. and perform
arithmetic conditionally. Multiplication
Arithmetic Conditionally: means that we The multiply() function multiplies the values from
can define conditions where the arithmetic one array with the values from another array,
operation should happen. and return the results in a new array.
All of the discussed arithmetic functions Multiply the values in arr1 with the values in
take a where parameter in which we can arr2:
specify that condition.
import numpy as np
Addition arr1 = np.array([10, 20, 30, 40, 50, 60])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.multiply(arr1, arr2)
The add() function sums the content of two print(newarr)
arrays, and return the results in a new
array.
Remainder
Raise the valules in arr1 to the power of The divmod() function return both the quotient
values in arr2: and the the mod. The return value is two arrays,
the first array contains the quotient and second
import numpy as np array contains the mod.
arr1 =
np.array([10, 20, 30, 40, 50, 60]) import numpy as np
arr2 = np.array([3, 5, 6, 8, 2, 33]) arr1 = np.array([10, 20, 30, 40, 50, 60])
newarr = np.power(arr1, arr2) arr2 = np.array([3, 7, 9, 8, 2, 33])
print(newarr) newarr = np.divmod(arr1, arr2)
print(newarr)
The example above will return [1000
3200000 729000000 6553600000000 2500 The example above will return:
0] which is the result of 10*10*10, (array([3, 2, 3, 5, 25, 1]), array([1, 6, 3, 0, 0,
20*20*20*20*20, 30*30*30*30*30*30 27]))
etc. The first array represents the quotients, (the
integer value when you divide 10 with 3, 20 with
7, 30 with 9 etc.
The second array represents the remainders of
the same divisions.
Absolute Values
import numpy as np
arr = np.array([-1, -2, 1, 2, 3, -4])
newarr = np.absolute(arr)
print(newarr)