Python Programming Student Notes
Python Programming Student Notes
+= Add AND: Add right side operand with left side operand and then assign to aa=a+b
left operand +
=
b
-= Subtract AND: Subtract right operand from left operand and then assign to aa=a-b
left operand -
=
b
*= Multiply AND: Multiply right operand with left operand and then assign to left aa=a*b
operand *
=
b
/= Divide AND: Divide left operand with right operand and then assign to left aa=a/b
operand /
=
b
%= Modulus AND: Takes modulus using left and right operands and assign aa=a%b
result to left operand %
=
b
//= Divide(floor) AND: Divide left operand with right operand and then assign the aa=a//b
value(floor) to left operand /
/
=
b
**= Exponent AND: Calculate exponent(raise power) value using operands and aa=a**b
assign value to left operand *
*
=
b
&= Performs Bitwise AND on operands and assign value to left operand aa=a&b
&
=
b
|= Performs Bitwise OR on operands and assign value to left operand aa=a|b
|
=
b
^= Performs Bitwise XOR on operands and assign value to left operand aa=a^b
^
=
b
>>= Performs Bitwise right shift on operands and assign value to left operand aa=a>>b
>
>
=
b
<<= Performs Bitwise left shift on operands and assign value to left operand aa= a << b
<
<
=
PG Program in Analytics
Python Programming Student Notes
DATA TYPES
EXAMPLE DATA TYPE
x = "Hello W orld" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", frozenset
"cherry"})
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
STRING OPERATIONS
FUNCTION DESCRIPTION
mystring[:N] Extract N number of characters from start of string.
mystring[-N:] Extract N number of characters from end of string
mystring[X:Y] Extract characters from middle of string, starting from X position and ends with Y
str.split(sep=' ') Split Strings
str.replace(old_substring, Replace a part of text with different substring
new_substring)
str.lower() Convert characters to lowercase
str.upper() Convert characters to uppercase
str.contains('pattern', case=False) Check if pattern matches (Pandas Function)
str.extract(regular_expression) Return matched values (Pandas Function)
str.count('sub_string') Count occurrence of pattern in string
str.find( ) Return position of sub-string or pattern
str.isalnum() Check whether string consists of only alphanumeric characters
str.islower() Check whether characters are all lower case
str.isupper() Check whether characters are all upper case
str.isnumeric() Check whether string consists of only numeric characters
str.isspace() Check whether string consists of only whitespace characters
len( ) Calculate length of string
cat( ) Concatenate Strings (Pandas Function)
separator.join(str) Concatenate Strings
BUILT-IN FUNCTIONS
FUNCTION DESCRIPTION
abs(x) Returns absolute value of a number
ascii() Returns ASCII value of a string
bin() Returns binary representation of an integer
bool() Converts value to boolean (True / False)
complex() Used to convert numbers or string into a complex number
dict() A constructor which creates a dictionary
dir() Returns a list of names in the current local space
float() Returns a floating point number from a number or string
format() Returns a formatted representation of a given value
frozenset() Returns an immutable frozenset object
globals() Returns a dictionary containing the variables defined in the global namespace
help() Used to get help related to the object passed during the call
input() Used to get input from the user
int() Returns the integer value of a number
iter() Returns an iterator object
list() Creates a list
locals() Returns a dictionary containing the variables defined in the local namespace
map() Returns a list of results after applying a given function to each item of an iterable
max() Returns a maximum value in the sequence
min() Returns a minimum value in the sequence
PG Program in Analytics
Python Programming Student Notes
LIST OPERATIONS
FUNCTION DESCRIPTION
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
TUPLE OPERATIONS
FUNCTION DESCRIPTION
all() Returns true if all elements are true or if tuple is empty
any() return true if any element of the tuple is true. if tuple is empty, return false
len() Returns length of the tuple or size of the tuple
enumerate() Returns enumerate object of tuple
max() return maximum element of given tuple
min() return minimum element of given tuple
sum() Sums up the numbers in the tuple
sorted() input elements in the tuple and return a new sorted list
tuple() Convert an iterable to a tuple.
SET OPERATIONS
FUNCTION DESCRIPTION
add() Adds an element to a set
remove() Removes an element from a set. If the element is not pr esent in the set, raise a KeyError
clear() Removes all elements form a set
copy() Returns a shallow copy of a set
pop() Removes and returns an arbitrary set element. Raise KeyError if the set is empty
update() Updates a set with the union of itself and others
union() Returns the union of sets in a new set
difference() Returns the difference of two or more sets as a new set
difference_update() Removes all elements of another set from this set
discard() Removes an element from a set if it is a member. (Do nothing if the element is not in the set)
intersection() Returns the intersection of two sets as a new set
intersection_update() Updates the set with the intersection of itself and another
isdisjoint() Returns True if two sets have a null intersection
issubset() Returns True if another set contains this set
issuperset() Returns True if this set contains another set
symmetric_difference() Returns the symmetric difference of two sets as a new set
symmetric_difference_update() Updates a set with the symmetric difference of itself and another
PG Program in Analytics
Python Programming Student Notes
DICTIONARY OPERATIONS
FUNCTION DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dictionary's (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.
CONDITIONAL STATEMENTS
STATEMENT SYNTAX EXAMPLE
if statement if <expression>: if x < y:
<body; body is executed if expression is true> print('yes')
if.. else statement if <expression>: if x < y:
<body; body is executed if expression is true> print('yes')
else: else:
<body; body is executed if expression in 'if' is false> print('no')
Nested if-else statement if <expression>: if time == 'morning':
<body; body is executed if expression is true> print('Good morning')
elif <expression>: elif name == 'afternoon':
<body; body is executed if 'elif' expression is true> print('Good afternoon')
elif <expression>: elif name == 'evening':
<body; body is executed if 'elif' expression is true> print('Good evening')
.... ...
else: else:
<body; body is executed if expression in 'if' is false> print("Good day")
For loop for i in sequence: for val in range(11):
<statement(s) of for > print(val)
While loop while <expression>: while value < 10:
<statement(s) of while; is executed till expression is true > print(value)
List Comprehension [ expression for item in list if conditional ] [ x : x**2 for i in range(100) if x%2 ==0
]
BASIC OPERATORS
LOGIC FUNCTIONS DESCRIPTION SYNTAX
2. Array contents
isfinite Test element-wise finiteness isfinite(x,l[, out, where, casting,
order ])
isinf Test element-wise for positive or negative infinity isinf(x,l[, out, where, casting,
order ])
isnan Test element-wise for NaN and return result as a boolean array isnan(x,l[, out, where, casting,
order ])
isneginf Test element-wise for negative infinity isneginf(x[,out])
isposinf Test element-wise for positive infinity isposinf(x[,out])
4. Comparison
allclose Return True if two array are element wise equal allclose(a1, a2)
isclose Return a boolean array if two array are element wise equal isclose(a1, a2)
array_equal True if two arrays have same shape and elements array_equal(a1, a2)
array_equiv Return True if input array are shape consistent and all elements equal array_equiv(a1, a2)
greater Return True if (x1>x2) greater(x1, x2)
greater_equal Return True if (x1>=x2) greater_equal(x1, x2)
less Return True if (x1<x2) less(x1, x2)
less_equal Return True if (x1=<x2) less_equal(x1, x2)
equal Return True if (x1==x2) equal(x1, x2)
not_equal Return True if (x1!=x2) not_equal(x1, x2)
2. Trigonometric function
sin() Trigonometric sine
cos() Trigonometric cosine
tan() Trigonometric tangent
arcsin() Inverse sine
arccos() Inverse cosine
arctan() Inverse tangent
hypot() Returns hypotenuse of right angled triangle
degree() Convert angles from radians to degrees
radianns() Convert angles from degrees to radians
3. Rounding
around() Evenly round to the given number of decimal
round() Round an array to the given number of decimals
floor() Return floor of input
ceil() Return the ceiling of the input
truncate() Return truncate value of the input before and after some ind ex
6. Arithmetic operations
add() Add arguments
reciprocal() Return reciprocal of arguments
negative() Numerical negative
multiply() Multiply arguments
divide() Divide arguments element wise
power() First array element raised to powers from second array
subtract() Subtract arguments element wise
SUMMARY STATISTICS
STATISTIC DESCRIPTION SYNTAX
Mean The sum of a collection of numbers divided by the count of numbers in the statistics.mean()
collection.
Median The middle most value in the list of numbers statistics.median()
Mode The value in the list of numbers which has the highest frequency statistics.mode()
PG Program in Analytics
Python Programming Student Notes
VISUALIZATION
Matplotlib import matplotlib.pyplot as plt
CHART DESCRIPTION
acorr Plot the autocorrelation of x
annotate Annotate the point xy with text text
arrow Add an arrow to the axes
axes Add an axes to the current figure and make it the current axes
axhline Add a horizontal line across the axis
axhspan Add a horizontal span (rectangle) across the axis
axis Convenience method to get or set some axis properties
axvline Add a vertical line across the axes
axvspan Add a vertical span (rectangle) across the axes.
bar Make a bar plot.
barbs Plot a 2D field of barbs.
barh Make a horizontal bar plot.
box Turn the axes box on or off on the current axes.
boxplot Make a box and whisker plot.
broken_barh Plot a horizontal sequence of rectangles.
clf Clear the current figure.
clim Set the color limits of the current image.
close Close a figure window.
cohere Plot the coherence between x and y.
colorbar Add a colorbar to a plot.
eventplot Plot identical parallel lines at the given positions.
figlegend Place a legend on the figure.
fignum_exists Return whether the figure with the given id exists.
figtext Add text to figure.
figure Create a new figure.
gca Get the current Axes instance on the current figure matching the given keyword args, or create one.
gcf Get the current figure.
grid Configure the grid lines.
hexbin Make a hexagonal binning plot.
hist Plot a histogram.
hist2d Make a 2D histogram plot.
legend Place a legend on the axes.
locator_params Control behavior of major tick locators.
loglog Make a plot with log scaling on both the x and y axis.
magnitude_spectrum Plot the magnitude spectrum.
margins Set or retrieve auto scaling margins.
matshow Display an array as a matrix in a new figure window.
minorticks_off Remove minor ticks from the axes.
minorticks_on Display minor ticks on the axes.
pause Pause for interval seconds.
pcolor Create a pseudocolor plot with a non-regular rectangular grid.
pcolormesh Create a pseudocolor plot with a non-regular rectangular grid.
phase_spectrum Plot the phase spectrum.
pie Plot a pie chart.
plot Plot y versus x as lines and/or markers.
plot_date Plot data that contains dates.
savefig Save the current figure.
sca Set the current Axes instance to ax.
scatter A scatter plot of y vs x with varying marker size and/or color.
show Display a figure.
stackplot Draw a stacked area plot.
stem Create a stem plot.
step Make a step plot.
subplot Add a subplot to the current figure.
PG Program in Analytics
Python Programming Student Notes
Chart DESCRIPTION
catplot() Figure-level interface for drawing categorical plots onto a FacetGrid.
stripplot() Draw a scatterplot where one variable is categorical.
swarmplot() Draw a categorical scatterplot with non-overlapping points.
boxplot() Draw a box plot to show distributions with respect to categories.
violinplot() Draw a combination of boxplot and kernel density estimate.
boxenplot() Draw an enhanced box plot for larger datasets.
pointplot() Show point estimates and confidence intervals using scatter plot glyphs.
barplot() Show point estimates and confidence intervals as rectangular bars.
countplot() Show the counts of observations in each categorical bin using bars.
relplot() Figure-level interface for drawing relational plots onto a FacetGrid.
scatterplot() Draw a scatter plot with possibility of several semantic groupings.
lineplot() Draw a line plot with possibility of several semantic groupings.
jointplot() Draw a plot of two variables with bivariate and univariate graphs.
pairplot() Plot pairwise relationships in a dataset.
distplot() Flexibly plot a univariate distribution of observations.
kdeplot() Fit and plot a univariate or bivariate kernel density estimate.
rugplot() Plot datapoints in an array as sticks on an axis.
lmplot() Plot data and regression model fits across a FacetGrid.
regplot() Plot data and a linear regression model fit.
residplot() Plot the residuals of a linear regression.
heatmap() Plot rectangular data as a color-encoded matrix.
clustermap() Plot a matrix dataset as a hierarchically-clustered heatmap.
Data Exploration
Function Description
df.info() Provides information like datatype, shape of the dataset and memory usage
df.describe() Provides information like count, mean, min, max, standard deviation and quantiles
PG Program in Analytics
Python Programming Student Notes
Filter data
Function Description
df.loc[condition] Returns the rows based on one condition
df[(condition) & (condition)] Returns the rows based on two conditions (& operator)
df[(condition) | (condition)] Returns the rows based on two conditions (| operator)
df.loc[(condition) & Returns the rows based on two conditions (& operator) using loc
(condition)]
df.loc[(condition) | (condition)] Returns the rows based on two conditions (| operator) using loc
Statistical Functions
Function Description
df.mean() Finds the mean of every column
df.median() Finds the median of every column
df.column_name.mode() Finds the mode of a column
df.corr() Creates a correlation table
df.max() Finds the max value from a column
df.min() Finds the min value from a column
df.std() Finds the standard deviation of each column
df.cov() Creates a covariance matrix
Write Data
Function Description
df.to_csv(file_name) Write the data from df to a csv file
df.to_excel(file_name) Write the data from df to an excel file
df.to_html(file_name) Write the data from df to a html file
df.to_sql(table_name, Write the data from df to a table in a database
connection_obje
df.to_json(file_name) Write the data from df to a json file
Duplicates
Function Description
df.duplicated(keep='first') Find the first occuring duplicates.
df.drop_duplicates(keep, Drop the duplicate rows
inplace)