Tuesday, 22 March 2022

Pandas#01

 PANDAS [Basics]..

Pandas is a library used for working with data series | data matrix | datasets.

Pandas is useful for  analyzing using stat, cleaning messy data sets, exploring, and manipulating data.

"Pandas" is  "Python  Analysis for Data" and was created by Wes McKinney in 2008.

Pandas can find correlation between two columns or more. Aggregate functions like sum, average, min, max etc. can be easily found.

It is used in Python using import pandas 

It is used to create, manipulate and extract Data Frames.

import pandas as pd
biodata = {
'Name':['Raj', 'Ram','Sita', 'Laks'],
'Age' :[ 23, 23, 24, 21],
}


biof1 = pd.DataFrame(biodata)
print('bio 1=', biof1)


"""
bio 1= Name Age
0 Raj 23
1 Ram 23
2 Sita 24
3 Laks 21
"""


import pandas as pd
biodata = {
'Name':['Raj', 'Ram','Sita', 'Laks'],
'Age' :[ 23, 23, 24, 21],
}
biof1 = pd.DataFrame(biodata)
print('bio 1=', biof1)


"""
bio 1= Name Age
0 Raj 23
1 Ram 23
2 Sita 24
3 Laks 21
"""


biof1.to_csv('bio.csv')  #to save in a bio.csv file

It can be saved using biof1.to_csv('bio.csv')

biodata1 = {
'Name':['Raj', 'Ram','Sita', 'Laks'],
# 'Age' :[ 23, 23, 24, 21],
'Qual' :[ 'UG','PG', 'Phd','Phd'],
"Status" :['s','s','m','b']}

Note Dictionary is converted to data frame by pd.Dataframe()

If we have another data frame biof2, we can add both as below:


biof2 = pd.DataFrame(biodata1)
print(biof2)
"""
Name Qual Status
0 Raj UG s
1 Ram PG s
2 Sita Phd m
3 Laks Phd b
"""

result = pd.concat([biof1, biof2])
print(result)
"""
Name Age Qual Status
0 Raj 23.0 NaN NaN
1 Ram 23.0 NaN NaN
2 Sita 24.0 NaN NaN
3 Laks 21.0 NaN NaN
0 Raj NaN UG s
1 Ram NaN PG s
2 Sita NaN Phd m
3 Laks NaN Phd b
"""

biof1 and biof2 are combined. But notice the print out with NaN values. Then how to add with out this problem.

result1 = pd.concat([biof1, biof2], axis = 1)
print(result1)
"""
Name Age Name Qual Status
0 Raj 23 Raj UG s
1 Ram 23 Ram PG s
2 Sita 24 Sita Phd m
3 Laks 21 Laks Phd b
"""
# if dfs are same then use append()
result1 = pd.concat([biof1, biof2], axis=1)

SO easy.. axis =1 means by columns.

Now let us see how Series can be defined. How Data Frames can be accessedby row using df.loc() and columns by df["colname"]:

#refer to the row index:
print('\n',df.loc[0]) # First Row only
"""First Row
Name Annamalai
Age 90
Name: 0, dtype: object
"""
print('\n',df.loc[0:1]) # First, Second Row only
"""

Name Age
0 Annamalai 90
1 AMET 29
"""

print('\n',df["Age"]) # Accessing only Age Column values
"""
0 90
1 29
2 25
3 20
Name: Age, dtype: object
"""

To read csv file and load in df DataFrame

df = pd.read_csv('bio.csv')
print(df)
"""
Unnamed: 0 Name Age
0 0 Raj 23
1 1 Ram 23
2 2 Sita 24
3 3 Laks 21
"""

To read JSON file and print

import pandas as pd
df = pd.read_json('data.json')
print(df.head(5).to_string())
"""
Duration Pulse Maxpulse Calories
0 60 110 130 409.1
1 60 117 145 479.0
2 60 103 135 340.0
3 45 109 175 282.4
4 45 117 148 406.0
"""
print(df.tail(5).to_string())
"""
Duration Pulse Maxpulse Calories
164 60 105 140 290.8
165 60 110 145 300.4
166 60 115 145 310.2
167 75 120 150 320.4
168 75 125 150 330.4
"""

Please note JSON = Python Dictionary . JSON objects have the same format as Python dictionaries.

Reading by load() and writing a JSON File using dump():


import json
with open('data.json') as f:
data = json.load(f)

with open('data_new.json', 'w') as f:
json.dump(data, f, indent=2)
print("JSON file created from data.json file")


Monday, 21 March 2022

Python#13 [Strings]

STRINGS

Prain Teaser 1:

import re
def clean_strings(strings):
result = []
print(len(strings))
for value in strings:
print(value)
value = value.strip()
value = re.sub('[!#?]', '', value)
value = value.title()
result.append(value)
return result

names = ['Rama ',' Laksmana',' Sita ']

print(clean_strings(names))

Result:

3
Rama
['Rama']

It is wrong out put. can you correct the code to get the out put as below. 

3
Rama
Laksmana
Sita
['Rama', 'Laksmana', 'Sita']


Other Useful Python String Operations 
#String

s1 = 'hello'
s2 = "Hello"
print(s1, s2) # hello Hello

docstr = """
This is multi line strings. Strings can be declared within \n Single quote \'
or Double Quote\" \n Note \ is used as escape character for quote.\n
String is an array of charecters just like in any other language.
"""
print(docstr)

hello = "Hello!"
for i in hello:
print(i) # To print character by character

# String functions


str = ' Mother, is superior, god '
print(len(str)) # 22
print('is' in str) # True
print('is' not in str) # False

print('was' in str) # False
print('was' not in str) # True

if 'was' not in str:
print('Was not present in Str')

# Slicing
print(str[:6]) # Mother : for from Beginning
print(str[0:6]) # Mother. Note 0 inclusive 6 exclusive
print(str[10:]) # T superior god : for up to end
print(str[-3:]) # God using negative indexing
print(str.upper()) # MOTHER IS SUPERIOR GOD
print(str.lower()) # mother is superior god
print(str.strip()) # Mother is superior god without spaces in the front and the end
print(str.replace("Mother", "Wife")) # Check Wife is superior God ...True!!!
print(str.split('.')) # [' Mother, is superior, god ']

s1 = 'Russia '
s2 = ' Ukraine'
s3 = 'x'
s4 = s1 + s3 + s2
print(s4) # Russia x Ukraine String Concatenation using +

# Formatting
lover = 'Juliat'
str = 'I am Romeo, i love\'o love {}'
print(str.format(lover)) # I am Romeo, i love'o love Juliat

times = 1000
str = 'I am Romeo, i love\'o love {} {} times' # many place holders {}
print(str.format(lover, times)) # I am Romeo, i love'o love Juliat 1000 times

str = 'I am Romeo, i love\'o love {1} times {0} ' # using Positional indexes
print(str.format(lover, times)) # I am Romeo, i love'o love 1000 times Juliat

str = "i love seetha ..mmm, \n also i love her sister <careless whisper>"
print(str) # using \n to new line : called as escape characters

print(str.title()) # I Love Seetha ..Mmm <CR> Also I Love Her Sister <Careless Whisper> Note capitals
print(str.split(',')) # ['i love seetha ..mmm', ' \nalso i love her sister <careless whisper>']
print("123".zfill(5)) #00123

str = 'sivaji vayile zilabee'
print(str[::-1]) # Reversal : # eebaliz eliyav ijavis

str1 = 'I am alive'
print(str1) # I am alive
del(str1)
#print(str1) # Name Error str1 is not defined

# String Alignment
str1 = "|{:<10}|{:^10}|{:>20}|".format('AMET', 'ODL', 'FOR E-Learning!')
# < for Left, ^ for Centre and > for Right
print("\nLeft, center and right alignment with Formatting: ")
print(str1) # print as below
"""#Left, center and right alignment with Formatting:
|AMET | ODL | FOR E-Learning!|"""
str2 = "\n{0:^12} was founded in {1:<4}!".format("AMET ODL FOR E-Learning!", 2022)
print('\n'+str1+'\n'+ str2)
"""
|AMET | ODL | FOR E-Learning!|

AMET ODL FOR E-Learning! was founded in 2022!
"""
In the above example various string operations are explained with the respective outputs as # comments

Happy Stringing in Python with AMET ODL ☝☝☝

Bonus :
{ for E-lite learners}
Jupyter Basics

You have to start with 

$ jupyter notebook

or

$ jupyter notebook --no--browser

Features ( Try these in Ipython)

  1. Tab Completion
  2. Introspection
  3. ? to display doc string
  4. %cmd anyScript.py where cmd = run. load etc.
  5. keyboard shortcuts like Unix bash shell
  6. Magic commands
    1. special commands not built in to python itself are known as magic commands
    2. Any command prefixed by %
    3. Eg. 
      1. aArray = np.random.randm(100,100)
      2. %timeit np.dot(aArray, aArray)
    4. %debug?
    5. %pwd
    6. %matplotlib inline
    7. eg: a ='apple'
      1. a <tab>
    8. duck typing

Python#12

Sets

Sets are used to store multiple items in a single variable

Sets are defined with {}.

Set is one of 4 built-in data types in Python used to store collections of data.

A set is a collection which is unorderedunchangeable*, and unindexed

Does not allow duplicate elements

set = {} will return data type as dictionary. SO we have to use set() method

to return <class: set>

Set Operations are explained in the following example code:



s1 = {}
print(type(s1))
#<class 'dict'>


s2 =set()
print(type(s2))
#<class 'set'>

s3 = set(("apple", "banana", "cherry")) # note the double round-brackets
print(s3) #{'banana', 'apple', 'cherry'}


aset ={1,2,3,4,5,5}
print(aset)
#{1, 2, 3, 4, 5}

aset =set("Hello")
print(aset)
#{'H', 'e', 'o', 'l'} -->order immaterial, only one l is printed


aset = set()
aset.add(11)
aset.add(22)
aset.add(33)


#aset.discard()
print(aset) #{33,11,22}
aset.pop()
print(aset) #{11,22}

#set Operations

odd = {1, 3, 5, 7, 9}
even = {0, 2, 4, 6, 8, 10}
primes = {3, 5, 7}

print(odd.union(even)) #{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

print(odd.intersection(primes)) #{3, 5, 7}

print(even.intersection(primes)) #set()

print(odd.difference(primes)) #{1, 9}

print(odd.symmetric_difference(primes)) #{1, 9}

print(odd.symmetric_difference(even)) #{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

a = {1,2,3,4,5,6,7,8,9}

b = {1,2,3,10,11,12}

a.update(b)

print(a) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

a.intersection_update(b)

print(a) #{1, 2, 3, 10, 11, 12}

a.add(13)
print(a) # {1, 2, 3, 10, 11, 12, 13}

print(b) #{1, 2, 3, 10, 11, 12}

b.pop()

print(b) #{2, 3, 10, 11, 12}

def odd_even():
n = int(input('EnterNumper < 10 Please')) #5
if n in odd:
print('Odd number')
elif n in even:
print('Even number')

# odd_even() # Odd Number

print(a.issuperset(b)) # True

print(a.isdisjoint(b)) # False


c ={7,8,9}

print(a.isdisjoint(c)) # True

d = c # copy the reference be careful when u change the original alsowill change
print(c,d) #{8, 9, 7} {8, 9, 7}
d.add(18)
print(c,d) # {8, 9, 18, 7} {8, 9, 18, 7} dangerous original also changed


c ={7,8,9}
d = c.copy()
d.add(18)
print(c,d) # {8, 9, 7} {8, 9, 18, 7}

The results are given in the same line as comments for easy reference and understanding.

Happy set learning with AMETODL😈😈😈

Sunday, 20 March 2022

Python#11 (Multi Processing)

 MULTI PROCESSING


How to make python do process simultaneously ?  Is it Possible? 

DO many things at a time? OMNI POTENT? 

Python supports multi processing. It utilizes the multi cores and Multi CPU's and speed up the process time.

Process:
  • Process is an instance of a program
  • Starting a process is slower that starting a thread
  • Larger memory footprint
  • IPC (inter-process communication) is more complicated

Thread

  • A thread is an light weight process  within a process that can be scheduled for execution               . 
  • A Process can spawn multiple threads.  
  • Key facts: - Multiple threads can be spawned within one process. Memory is shared between all threads 
  • Starting a thread is faster than starting a process - Great for I/O-bound tasks - Light weight - low memory footprint
  • One GIL( Global interpreter lock) for all threads, i.e. threads are limited by GIL 
  • Multithreading has no effect for CPU-bound tasks due to the GIL - Not interruptible/killable -> be careful with memory leaks - increased potential for race conditions

In this, we will take care  of Multiprocessing. Multithreading, we will take later. Open PyCharm IDE. Open project. Give any name as project name. In main.py. Type in /copy paste the following code and Run. It is Simple Processing to multiply.  

import time

start =time.perf_counter()

def multiplication_table(begin, end):

for i in range(begin, end+1):

for j in range(begin, end+1):
#temp = i * j

print(f'{i:<4}*{j:4} ={i * j:6}')

multiplication_table(1,5000)

finish =time.perf_counter()

print(f'\nSingle Finished in {round(finish-start, 2)}second(s)')

"""
Single Finished in 510.05second(s)
"""
Let us Multiprocessing the same print multiplication operation for  P1, 5000 using 5 Processes P1 with 1,1000, P2 with 1001,2000, P3 with 2001 to 3000, P4 with 3001 to 4000, P5 with 4001 to 5000.


import multiprocessing

import time


start=time.perf_counter()


def print_multi(begin, end):

for i in range(begin, end + 1):

for j in range(begin, end + 1):

temp = i * j

print(f'T{i:<4}*{j:4} ={i * j:6}')

if __name__ == "__main__":


p1 = multiprocessing.Process(target=print_multi, args=(1, 1000))
p2 = multiprocessing.Process(target=print_multi, args=(1001, 2000))
p3 = multiprocessing.Process(target=print_multi, args=(2001, 3000))
p4 = multiprocessing.Process(target=print_multi, args=(3001, 4000))
p5 = multiprocessing.Process(target=print_multi, args =(4001, 5000))

p1.start()
p2.start()
p3.start()
p4.start()
p5.start()

p1.join()
p2.join()
p3.join()
p4.join()
p5.join()
# print("Done")
finish = time.perf_counter()

print(f'MULTI in {round(finish-start, 2)} seconds (s)\n')

"""
MULTI in 80.44 seconds (s)
"""

See the difference  510.05  - 80.44 =     429.61 seconds

For Many Processes, You can save Time. You can spend this quality time with your family 🐤🐤🐤 

Happy Digital Learning with AMET!!!

Python # 10 : IF( COMPATIBILITY OF MARRIED COUPLES).

IF ..ELSE ..IF (again)

Let us have fun!. 

We see the married couple are compatible or not in Python?

Syntax for IF clause is very super simple.

Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

A simple IF statement.

if a>10:

    print('a is greater than 10')

else:

    print('Not greater than 10)


if CONDITION1:

   do something
elseif CONDITION2:
   do this thing:
else:
        do unsatisfied condition things

How it can for us to see the couple's Compatibility! hey .. wait .. wait.. wait..

Ask the names of couples

Check whether their names consists of letters T, R,U, E, L,O,V, E

count those letters

if sum >50, they are absolutely compatible. or not.!

let us code this as follows:


name1 = input("Enter Husband Name ").lower()
name2 = input("Enter Wife's Name ").lower()
Total_TRUE = name1.count('t') + name2.count('t') + name1.count('r') + name2.count('r') + name1.count('u') + name2.count('u') + name1.count('e') + name2.count('e')
A = str(int(Total_TRUE))
Total_LOVE = name1.count('l') + name2.count('l') + name1.count('o') + name2.count('o') + name1.count('v') + name2.count('v') + name1.count('e') + name2.count('e')
B = str(int(Total_LOVE))
score = int(A + B)

if score < 10 or score >90:
print(f"Your score is{score}%, you go together like coke and mentos.")
elif score >40 and score < 50:
print(f"Your score is {score}%, you are alright together")
else:
print(f"Your score is {score}% Compatible")

Result:  Suppose if I give two names like DHANUSU and ISHU


Enter Husband Name DHANUSU
Enter Wife's Name ISHU
Your score is 30% Compatible

Process finished with exit code 0

Python says these names are less compatible.

Hooray, Python found out the reason for Divorce?😄 No  fault of Individuals !!!👨👩


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.👦👧

index.html

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