Thursday, 10 March 2022

Python#09

Data Cleaning

Normally data is available with missing values, Null values, incorrect values,  and inappropriate values 

Major problem is missing values. It is very very common in real time.

How we can handle those values in python? Let us see.


# import the pandas library

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',
'h'],columns=['one', 'two', 'three'])

df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])



Result:

        one       two     three

a  0.335319 -0.298568 -2.062935

b       NaN       NaN       NaN

c -1.739043 -0.912386 -0.675446

d       NaN       NaN       NaN

e -0.462957 -1.445715  1.483821

f  0.901405 -1.162616  0.173550

g       NaN       NaN       NaN

h -0.736636  1.685347  1.091092

In the above data frame ,  we could  see NaN, not a Number.

Let us take another case for missing values.


import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',
'h'], columns=['one', 'two', 'three'])

df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])

print(df['one'].isnull())

Result: 

a    False

b     True

c    False

d     True

e    False

f    False

g     True

h    False

Ok. Now we know the problem. How to rectify that. How to clean that.

Replace NaN with 0. 

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3, 3), index=['a', 'c', 'e'],columns=['one',
'two', 'three'])
df = df.reindex(['a', 'b', 'c'])
print(df)
print("C..NaN replaced with '0':")
print( df.fillna(0))

Result:

        one       two     three

a  0.373935 -1.487100 -0.272034

b       NaN       NaN       NaN

c  0.686059  0.286542 -0.093683

C..NaN replaced with '0':

        one       two     three

a  0.373935 -1.487100 -0.272034

b  0.000000  0.000000  0.000000

c  0.686059  0.286542 -0.093683

Now we fill with 'pad' as shown below in the python script.


import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',
'h'],columns=['one', 'two', 'three'])
df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])

print( df.fillna(method='pad'))

.Result:


"""
one two three
a -1.764189 1.336129 0.512163
b -1.764189 1.336129 0.512163
c 1.495126 -0.165035 -1.719821
d 1.495126 -0.165035 -1.719821
e 1.273926 0.606101 1.416004
f 1.901047 1.813446 -0.263735
g 1.901047 1.813446 -0.263735
h -1.900605 0.052075 -2.418204

"""
Drop Missing Values by the following Example.

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',
'h'],columns=['one', 'two', 'three'])

df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print(df.dropna())

Result:

"""
one two three
a 1.177113 -0.471903 -0.779807
c -0.917548 -0.478030 0.128027
e -1.579338 0.950953 -2.017034
f -0.050153 -0.419798 -0.007029
h 1.207687 -1.491949 -0.895676
"""
Comparing the above two outputs, we clearly notice that rows b, d, g are dropped.
Replace missing values with scalar  value are similar to  fillna() function as shown below :

import pandas as pd
import numpy as np
df = pd.DataFrame({'one':[10,20,30,40,50,2000],
'two':[1000,0,30,40,50,60]})

print(df.replace({1000:10,2000:60}))

Result:

"""
one two
0 10 10
1 20 0
2 30 30
3 40 40
4 50 50
5 60 60
"""

Hope fully from the above examples we understand the functions.
Happy Cleaning data with Python and  Enjoy learning with Python!!!

Wednesday, 9 March 2022

Data Story Telling

Data STORY Telling

We know 'Patti Vada sutta Katahai'.  

AGEOLD grandma stories for kids to engage and give moral instruction. In Tamil it is well known.

ஒரு ஊரில் பாட்டி ஒருத்தி வடை சுட்டு விற்று வந்தாள். ஒரு நாள் அவ்வழியாக பறந்து வந்த காக்கா ஒன்று ஒரு வடையை தூக்கிக்கொண்டு பறந்து போய் மரக்கிளை ஒன்றில் உட்கார்ந்து கொண்டது. அந்த வழியாக வந்த நரி, வடையோடு காக்காவை பார்த்துவிட்டது; வடையைத் தான் எடுத்துக்கொள்ள ஒரு தந்திரம் செய்தது. காக்காவைப் பார்த்து காக்கா, நீ மிகவும் அழகாக இருக்கிறாய். உனக்கு குரலும் கூட அழகாக இருக்கக்கூடும், ஒரு பாட்டுப் பாடு என்றது. காக்கா தன் வாயைத் திறந்து "கா.. கா..." என்று பாட்டுப் பாடவே வாயிலிருந்த வடை கீழே விழுந்துவிட்டது. நரி வடையை கவ்வி எடுத்துக்கொண்டு போனது.

Moral of the story. If you cheat somebody, You will be cheated by some body else. 

Visually : Kids Story

Other intelligent Version of this Story.

வடையைக் காலில் வைத்தபடி பாட்டுப் பாடியது ...காகம் ஏமாறவில்லை.! நரி கேட்டது...அழகாகப் பாட்டுப்பாடினாய் இனி ஒரு நடனம் ஆடு என்று..காகம் மீண்டும் வடையை வாயில் வைத்துக் கொண்டு நடனம் ஆடியது. நரி மீண்டும் ஏமாந்தது. நரி யோசித்துவிட்டு....பாட்டும் பாடினாய்..ஆடியும் காட்டினாய், அற்புதம்...இனி ஆடலுடன் பாடலும் பாடி...ஒரு நாடகம் நடி பார்க்கலாம் என்று கேட்டது. காகம் மீண்டும் வடையைக் காலில் வைத்துக் கொண்டு,,நான் பாடினேன் ஆடினேன்...நாடகம் நடிப்பதற்கு சக்தி வேண்டும் இந்த வடையை சாப்பிட்ட பின்னர் நடித்துக் காட்டுகிறேன் நண்பனே என்றது. நரி மீண்டும் ஏமாறியது.

How to impress the kids. Like above. The same way we have to impress the audience. When we say with statistics (White lies), Many of them could not understand. 

So Hello the so called Data scientist or Data Analyst, All of you, Listen.

you have to engage target audience with story lectures for subjects with stories full of numbers, charts and action insights.

Let us see how we can, with the help of python a simple, super and popular sample case.  

Why CSK keeps Dhoni ('Thala')  as Captain.

Everybody may fight with you. BCos, in Cricket kingdom, He is 'ALMIGHTY, GOD'.

Any way, assume CSK management scientifically substantiate the decision of keeping 'Thala'  Dhoni as Captain.



Take IPL data from web site, say two columns, year and Batting average for the respective years. Let us key in any IDE like PyCharm as below:


import matplotlib.pyplot as plt

import numpy as np

# # MS Dhoni IPL Batting Average Scores Across Seasons (2010-2019) #

X = np.array([2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019])

ms_dhoni = np.array([31.88, 43.55, 29.83, 41.90, 74.20, 31.00, 40.57, 26.36, 75.83, 83.20])

plt.scatter(X, ms_dhoni)

plt.savefig('thala0.jpg')

plt.show()

Scatter Plot will show points (year, Batting Average). Hey, Super simple coding in Python. Just 5 lines of code....👌

Result:


fig, ax = plt.subplots(1, 2, figsize=(13, 6))
ax[0].scatter(X, ms_dhoni)
ax[1].plot(X, ms_dhoni)
plt.xlabel('Year')
plt.ylabel('Average')
plt.savefig('thala1.jpg')
plt.show()


Result:

Take IPL data from web site, say two columns, year and Batting average for the respective years. Let us key in any IDE like PyCharm as below:


Left Side is the same old scatter. On right, we can see Line Chart.


Let us dig further. So data with no action. Insightful Key decision Support.


With this can we or CSK management can take a decision. No. I'm possible!


Let us see the trend line (borrowed from our Statistical Teacher (Was ..Boring.. Now Pouring..). By fitting the points with curve using polyfit() function.

fig, ax = plt.subplots(1, 2, figsize=(13, 6))
fig.text(0.5, 0.04, 'Years', ha='center', fontsize=18)
fig.text(0.04, 0.5, 'Average Scores in Seasons', va='center', rotation='vertical', fontsize=18)
fig, ax = plt.subplots(1, 1, figsize=(10, 8))
z = np.polyfit(X, ms_dhoni, 1)
p = np.poly1d(z)
plt.plot(X,p(X),"r--")
plt.xlabel('years')
plt.ylabel('Batting Average')
plt.savefig('thala2.jpg')
plt.show()


Video Link 


Result:


Let us overlap the line with trend line.


plt.plot(X, ms_dhoni)
plt.savefig('thala3.jpg')
plt.show()


Result

Eurekha.?! The above graph shows some thing...


Teacher reminded me in Stat Class . Positive Slope 👆->


Good Trends-> Improvement ✌; Here Better Batting Average for Dhoni 'Thala'...

The Decision taken by CSK management is perfectly right㊣ one.. 
[Whisper💪 --->.U need stat, Plot... to say this ?. Funny?--]


So with data, with some useful visualization of perfect graphs, we could communicate with  actions and insights.


Data storytelling is the ability to effectively communicate insights from a dataset using narratives and visualizations. It can be used to put data insights into context for and inspire action from your audience.


Wish you Good Luck CSK for forth coming IPL Seasons.💪 Like this we can use mere numbers to visual pleasure so that the audience will immerse and understand the key insights behind the data.


Happy Open and Distance Learning with AMET-ODL.👦👧

Tuesday, 8 March 2022

Python#08

Dictionary📘

Dictionaries are wonderful data structure available in python. 

Most of the elements/Building Blocks are dictionary in python.

Defined as An associative array or collection, where arbitrary keys are mapped to values.

Keys are much like a set. Keys are real keys for Dictionary manipulation.

Dictionary maps keys to values. It is Ordered data structure.

Dictionary is iterable. Supports access by integer indices.

#Creating
dict = {'slNo': 1,
'name':'Ram',
'sal':1200000
}

# Accessing by Key
print(dict['slNo'])
print(dict['name'])
print(dict['sal'])

Result:

1
Ram
1200000

In thee above see the dictionary creation with keys as slNo, name, sal. You can have anything as a key.

You can access by key as show n above. For eg dict['name'].


# print only keys
for key in dict:

print(key)

Result:

slNo
name
sal

# print only Values
for key in dict:
print(dict[key])

Result:

1
Ram
1200000

#print the whole dictionary
print(dict)

Result:

{'slNo': 1, 'name': 'Ram', 'sal': 1200000}


items = dict.items()
print(items)

Result:

dict_items([('slNo', 1), ('name', 'Ram'), ('sal', 1200000)])

Print individual key, value pair by iteration since it is iterable.


#iterating by .items()
for item in dict.items():
print(item)

Result:

('slNo', 1)
('name', 'Ram')
('sal', 1200000).

Please note this with curly brackets. '()'

########### Printing key value pair as tuple...Unpacking
for key, value in dict.items():
print(key,':',value)
############

Result:

slNo : 1
name : Ram
sal : 1200000

Modifying the value for key 'slNo' 


##Modifying value
dict['slNo'] = 999
print(dict)

Result:
{'slNo': 999, 'name': 'Ram', 'sal': 1200000}

Deleting a Key. Please note clear() function will delete the whole dictionary


#remove a single key and value
del dict['slNo']
print(dict)

Result:

{'name': 'Ram', 'sal': 1200000}

Please you try this piece of code at the end of this tutorial.


dict.clear();
print(dict,type(dict))

 Result:

{} <class 'dict'>

Adding a new Key 'SLNO', value 12345 pair 


print(dict)
dict['SLNO'] = 12345
print(dict)

Result:

{'slNo': 1, 'name': 'Ram', 'sal': 1200000}

{'slNo': 1, 'name': 'Ram', 'sal': 1200000, 'SLNO': 12345}

Let us have a break. We play with some funny example. In the above dictionary, can you try to transmit key as values and values as keys. Yeah.. You can do it with this piece of code, man!! with comprehensive iteration as show with for..loop.....

#Brain stormer Comprehensive to switch v->k, k->v
print(dict)
switch_key_value = {value: key for key, value in dict.items()}
print(switch_key_value)

Result:

{'slNo': 1, 'name': 'Ram', 'sal': 1200000}

{1: 'slNo', 'Ram': 'name', 1200000: 'sal'}

Sorting: Super easy in dictionary by keys or values.

Creating dictionary by keys for sorting() sample
dicts = {'apple':10000, 'orange':7000, 'bananna': 12000 }
for k in sorted(dicts):
print(k,'=',dicts[k])
print(30*'#','Sorted by Keys')

Result: (sorted by Keys)

apple = 10000
bananna = 12000
orange = 7000

########################### Sorted by Keys

#Function to return values
def by_value(item):
return item[1]

print(10*'#', 'sorting dictionary by values#')
#Iteartion for sorting the dictionary by values
for k, v in sorted(dicts.items(), key = by_value):
print(k,'=',dicts[k])

print(10*'#', 'with out bothering keys sorting only by values#')
for value in sorted(dicts.values()):
print(value)

Please note a function is defined to return values.

########## sorting dictionary by values#
orange = 7000
apple = 10000
bananas = 12000
#### with out bothering keys sorting only by values#
7000
10000
12000

Hope you learned some of the very basics of python Dictionary. Happy Learning.😊😊😊😊

Python#07

Class in Python

A Class in Python is a logical grouping of data and functions. It gives the freedom to create data structures that contains arbitrary content and hence easily accessible.

Class” is a logical grouping of functions and data. Python class provides all the standard features of Object Oriented Programming.

Class inheritance mechanism :  A derived class that override any method of its base class. A method can call the method of a base class with the same name. Python Classes are defined by keyword “class” itself. Inside classes, you can define functions or methods that are part of the class

Everything in a class is indented, just like the code in the function, loop, if statement, etc.

The self argument in Python refers to the object itself. Self is the name preferred by convention by Pythons to indicate the first parameter of instance methods in Python

Python runtime will pass “self” value automatically when you call an instance method on in instance, whether you provide it deliberately or not

In Python, a class can inherit attributes and behavior methods from another class called subclass

class ametClass():
def aMethod(self):
print("Men Money Machine & Matters")

def bMethod(self, param):
print("Hey I am testing class method :" + param)

def main():
c = ametClass()
c.aMethod()
c.bMethod('I am param porul')

main()

Result:

Men Money Machine & Matters

Hey I am testing class method :I am param porul

####inheritance

class aClass():

def aMethod(self):
print('A ha : Base class method 1')

def bMethod(self, str):
print('oh oh Base class method 2 '+str)

class childClass(aClass):

def cMethod(self):
aClass.aMethod(self) # Note instance of base class method
print('A ha : Child class Method1.....')

def dMethod(self, str):
print('Oh Oh Child class method 2'+str)

def main():

c1 = aClass()
c1.aMethod() # Note child inherited from aClass
c1.bMethod('Base class ..nna') # Note child inherited from aClass

c2 = childClass()
c2.aMethod()
c2.bMethod('Besh besh Child Class Method1')
c2.cMethod()
c2.dMethod('Nanna Irukku Child Class Method 2')

main()

Result

A ha : Base class method 1

oh oh Base class method 2 Base class ..nna

A ha : Base class method 1

oh oh Base class method 2 Besh besh  Child Class Method1

A ha : Base class method 1

A ha : Child class Method1.....

Oh Oh Child class method 2Nanna Irukku Child Class Method 2

Using Constructors
# Constructors : Defining and initalizing  values

class Cadet:

name = " " # Class Variables
def __init__(self, name):
self.name = name

def printWelcome(self):
print('Welcome to Kalvi Koil, AMET '+ self.name)

Cadet1 = Cadet('Anbu')

Cadet1.printWelcome()

Result :

Welcome to Kalvi Koil, AMET  Anbu

The above sample codes explain the how to define a class, define class method, inherit a class, overloading a method, initialize the class using constructor.

Happy Learning by simple super code!

Python#06

 Python Yield

yield is not like return. When return is used it is given to caller. When yield is used you can iterate, pass or suspend. Le us see with example. Ready guys! Start.. Here you go..

Here is the situation when you should use Yield instead of Return

Use yield instead of return when the data size is large

Yield is the best choice when you need your execution to be faster on large data sets.

Use yield when you want to return a big set of values to the calling function. 

Yield is an efficient way of producing data that is big or infinite.
yield wont take memory. 

Execution is faster The yield keyword in python works like a return with the only difference is that instead of returning a value, it gives back a generator function to the caller. 

A generator is a special type of iterator that, once used, will not be available again. 

The values are not stored in memory and are only available when called.

The values from the generator can be read using for-in, list() and next() method.

The main difference between yield and return is that yield returns back a generator function to the caller and return gives a single value to the caller.

Yield does not store any of the values in memory, and the advantage is that it is helpful when the data size is big, as none of the values are stored in memory.

The performance is better if the yield keyword is used in comparison to return for large data size.

# Yield is just like return but with generator(?) objects instead of values
Generators are special functions that have to be iterated to get the values
# To get the values the
# To get the values the objects has to be iterated
#Syntax yield expression
# #Sample yield function
# def demoyield():
# yield "Welcom to AMET - Pioneer in Maritime Education"
#
# out = demoyield()
# print(out)
# #<generator object demoyield at 0x000002802AC5DA50>
# # iterate to get the value in the above object
# #Generators are functions that return an iterable generator object. The values from the generator object are fetched one at a time instead of the full list together and hence to get the actual values you can use a for-loop, using next() or list() method
# for i in out:
#.      print(i)
# Example 2
# def gen():
#       yield 'G'
#.      yield 'A'
#       yield 'N'
#       yield 'D'
#       yield 'H'
#       yield 'I'
#       yield ' '
#       yield 'M'
#       yield 'A'
#       yield 'H'
#       yield 'A'
#       yield 'N'
#
# demo = gen()
#
# for i in demo:
#.      print(i)
#
#example 3 difference between normal function and generator function
#Normal
def normalfun():
     return 'Hello Zoox Robo Taxi to Universe - normal function'
def genfun():
       yield "'Hello Zoox Robo Taxi to Universe - generator function"

print(normalfun())
print(genfun())
# Hello Zoox Robo Taxi to Universe - normal function
#until it prints the whole string normalfun()wont stop
# <generator object genfun at 0x00000298E53AD900>
#but gen iterates so we can use the generator obhject to get the values and also , 'pause' and 'resume'
print(next(genfun()))
#Note next function
print(list(genfun()))

Python#05

 File Operations in Python

How to open a file, read, print, write, append the contents.?  All shown with the following example code and output

 # Simple Excel file read


import pandas as pd

csv_file = pd.read_csv('csv.csv')

print(csv_file)


# # printed the following
# h1 h2 h3 h4
# 0 1 2 3 4
# 1 5 6 7 8
# 2 9 10 11 12
# 3 13 14 15 16
# ##################
#Excel file sheet1 reading specific

excel_file = pd.read_excel('sample.xlsx', sheet_name='Sheet1')

print(excel_file)

# Print out
# Unnamed: 0 slno name age sal
# 0 1 1 1 1 1
# 1 2 2 2 2 2
# 2 3 3 3 3 3
# 3 4 4 4 4 4
# read multiple sheets

df_sheet_multi = pd.read_excel('sample.xlsx', sheet_name=['Sheet1', 'Sheet2'])

print(df_sheet_multi)

#Printout
# {'Sheet1': Unnamed: 0 slno name age sal
# 0 1 1 1 1 1
# 1 2 2 2 2 2
# 2 3 3 3 3 3
# 3 4 4 4 4 4, 'Sheet2': Unnamed: 0 slno name age sal
# 0 1 11 11 11 11
# 1 2 22 33 44 55
# 2 3 66 66 66 66
# 3 4 77 77 77 77}

print(25*'-','Sheet1')

print(df_sheet_multi['Sheet1'])


# ------------------------- Sheet1
# Unnamed: 0 slno name age sal
# 0 1 1 1 1 1
# 1 2 2 2 2 2
# 2 3 3 3 3 3
# 3 4 4 4 4 4

print(25*'-','Sheet2')

print(df_sheet_multi['Sheet2'])


# ------------------------- Sheet2
# Unnamed: 0 slno name age sal
# 0 1 11 11 11 11
# 1 2 22 33 44 55
# 2 3 66 66 66 66
# 3 4 77 77 77 77

# To Create and write contents

f = open("demo.txt", "w")

f.write("I have written the contents!")

f.close()



#open and read the file after the appending:
f = open("demo.txt", "r")

print(f.read())

#prints => I have written the contents!
f.close()


f = open("demo.txt", "a")

f.write("Now I have written the contents more again !")

f.close()

#In demo.txt => I have written the contents!Now I have written the contents more again !

import os.path

file_exists = os.path.exists('readme.txt')

print(file_exists)

#False

import os.path

file_exists = os.path.exists('demo.txt')

print(file_exists)

#True

f = open("demo1.txt", "w")

f.write("I have written the contents!")

f.close()


f = open("demo2.txt", "w")

f.write(str(list(csv_file)))


f = open("demo2.txt","r")

print(f.read())

#f.close()

print(f.read())

#Print ['h1', 'h2', 'h3', 'h4']


Hope The above simple code snippets and printouts shown as comments is clear and understandable. Happy Open and Distance Learning!

index.html

Mobile Tea/Coffee POS Chai POS Mobile Tea/Coffee & Snacks Billing ...