Basics Of Python For Data Science

INTRODUCTION:

Purpose of this blog is to help people who are eager to learn Python for DATA SCIENCE but don’t know how to start and where to begin. 

I just started to learn python and here I am going to share my learning experience and only the basic and relevant concepts in python for data science application.

Prerequisite

Basic understanding of any of the programming knowledge, Interest towards Data science and Python.

Why PYTHON

Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.


Though Python has wide variety of modules like Django/Flask, we are just going to focus only on the machine learning/Data science packages in python.

Please find the detailed information about python here:  Link

you can find some handy resources for python in this link:  

https://www.python.org/doc/

Basics

Variable assignment:

Unlike other high level programming language, we can directly assign and return the variable. below are eg. 

>>a=5 # to  assign value 5 to variable a (Note: # key used for comments )

To print the value of a, either of the below following methods can be used.

>>a

>>print a

Note: you don’t need to specify the variable type like C program. based on the value we assign to variable , python will default the variable type.

Eg:  >>x = ‘Python’ # variable type will be string

        >>y = 01 # variable type will be int

        >>x,y # will return x and y value

        >>type(a) # will return the type of variable ‘a’

STRING

String follows an array concept and it contains character variable. 

Syntax:

>>x= ‘Apple’ # should be in quotes

>>len(x) #return length of the variable x that is 5

How to return particular char from string :


>>x[len(a)-1] # will return only the last char from string ‘e’.

>>x[len(a)-2 ::] # will return 2nd char till end, :: tells to return value from -2 index position

>>x[:: -1] #will reverse the string

>>x[0] # will return 0th index value ‘A’

Note: When returning string by reading left to right, we mention index value as 0. by reading from right to left, should mention index as -1

Eg:

0 1 2 3 4

A|p|p|l|e

-5-4-3-2-1

To list the methods:

>>dir(str) # will return all available methods for string

 Same for all other objects like dir(int), dir(list)..etc

Some Important methods in string:

'capitalize',
 'center',
 'count',
 'decode',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'index',
 'isalnum',
 'isalpha',
 'isdigit',
 'islower',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',

‘zfill’

1. Capitalize

As it name sounds, this method will be used to capitalize the first letter of string.

Eg: 

>>A= ‘python’

>>A.capitalize() # will return the first letter of string to the capital one.

Result: ‘Python’

2. center

This  method is used to fill the specific characters at the start and end of the string with the given  length (No worries, its not difficult as it sounds)

Eg:

>> z= ‘i love mom’

>>z.center(15,’a’)   # int 15 says that string which we going to return must be the length of 15, if it is not already then we have to make it by adding mentioned char ‘a’ . Here in our example ‘i love mom’ is 10 char length, as per our code , it will be a 15 char length string by adding  three ‘a’ at the start and two ‘a’ at the end. 

    

Result: ‘aaai love momaa‘

What if int value mentioned in code is same as original string length?

>>z=’i love mom’ # 10 char length

>>z.center(10,’a’) # a will not be added to the existing string since it is already 10 char length

Result: ‘i love mom’

Note: you can get the functionalities of all the methods under string by following comment

>>help(str.method name) 

Eg: 

>>help(str.center)

3.count

This is used to return the number of occurrence of particular character or sub string inside the original string.

Eg:

>>A= ‘python2 wins python3’

>>A.count(‘python’) # will return the count of sub string python 

Result: 2

>>A.count(‘o’,2,19) # will return number of occurrence of ‘o’ from 2nd index to 19th

Result: 2

4. endswith

Return ‘True’ or ‘False’  by checking if string ends with a specified character.

Eg:

>>A= ‘Live good’

>>A.endswith(‘d’)

Result: True

>>A.endswith(‘f’)

Result: False

 

5. find

Used to find the index position of given character


Eg:

>>A=’Learn python’

>>A.find(n) # will return index value 4, you may wonder why its not returning the index value of ‘n’ in sub string python, reason is find() will consider only the first occurrence of given char or sub string.

Result: 4

What if mentioned char or sub string not exist in original string?

Eg:

>>A.find(‘x’) # As given char not exist in original string it will return -1 as index value

6. index

Everything is same as find() method but only difference is it will throw value error if mentioned char not exist in original string.

7. format

format is used to add the new string to the existing curly braces, curly braces are place holders of the arguments to be placed.


Eg:

>>A=’New {} boy’

>>print(A.format(‘baby’)) # curly braces will be replaced by format string ‘baby’

Result: ‘New baby boy’

8.Boolean methods:

There are few methods in string used to check the string and return true or false statement.

Eg:

>>a=’Ram’

>>a. isalpha() #will check if string a is full of alpha or not, if yes then will return yes

Result: YES

Same as above we have few other methods, listed below. Not explaining all those since they all have similar functionality.

>>isalnum(), isdigit(), islower(), isupper(), istitle(), isspace()

9. Join:

One of the important method under string concept , will be used frequently whenever we    

want to concatenate sequence of string using special character.

Eg:

>> Y= ‘python’,’cython’,’jython’

>> ‘-‘.join(Y)# will be concatenated using ‘-‘

Result:

‘python-cython-jython’

>>”.join(Y)# will be concatenated by space

10. Ljust:

left justification will be done as per given string length inside the method, with specified character padding.


Eg:

>> A=’Python’

>>A.ljust(10,’x’) # if specified char length 10 exceeds the actual string length then remaining char will be filled by specified char in method

Result:

‘Pythonxxxx’


>> B=’Python’

>>B.ljust(10) #since padding char not specified , default padding space(‘ ‘) will be taken.

Result:

‘Python    ‘

11.lower


Used to convert the given string with upper case to lower case.

>> B.lower()

Result:

‘python’

12. lstrip vs rstrip vs strip:


Removes the white space or specified char from string in left justified.

Eg:

>>C=’    python     ‘

>>C.lstrip() #will remove the white space in left justified

Result:

‘python    ‘


>>C.lstrip(‘    pyt’) #will remove char ‘pyt’ by reading left to right.

Result:

‘hon   ‘


rstrip() is same as above but will be used to remove the char by reading right to left.


Eg:

>>C.rstrip() #will remove the space in right justified.

Result:

‘   python’


strip() , used to remove specific char from both beginning and end of the string.


Eg:

>>C.strip()

Result:

‘python’ 

13.split:

To break the string at separator and returns the list of strings


Eg:

>>text=’ I love python’

>>text.split() # will split the string based on number of spaces’

Result:

[‘I’,’love’,’python’]


>>team=’india , aus , ban’

>>team.split(‘,’) #will break the string based on number of ‘,’

Result:

[‘india’, ‘aus’ , ‘ban’]

14. splitlines:


As it name sounds, this method used to split the lines in to list.

Eg:

>>string = ‘Welcome everyone to\nthe world \nof python’

>>print string

>>string.splitlines()


Result:

Welcome everyone to

the world

of python


[‘Welcome everyone to’ , ‘the world’ , ‘of python’]

15. swapcase:

To swap the string from upper case to lowercase and vice versa

Eg:

>>A=’python’

>>A.swapcacse()

Result:

‘PYTHON’

16. Zflil

This one is more similar to ljust() which we have seen earlier, only difference is we cannot specify  the char that will be used for padding and by default it will be padded by ‘0’.


Eg:

>>s=’python is case sensitive’

>>s.zfill(30)

Result:

‘000000python is case sensitive’


 

And yeah!! We are done with the overview of string concepts in python . Please go ahead and practise all the string function for different use cases.you can get plenty of handson exercise here




Take chance, make mistakes. That’s how you grow!!!


Things to remember:

To know about list of methods available in each data type –> dir(datatype). Ex: dir(string),dir(int),dir(list)..etc
To get to know brief description about each function –> help(datatype.function). Ex:help(string.center)

ARRAYS

  • What is Array? what is it purpose!! so Array is a data structure which can store fixed size collection of elements of data types. Simply, Array is a collection of variable of same or different data type.

Types of Array in Python:

  • List Array
  • Tuple Array
  • Dictionary
  • Set Array

1.List Array:

  • First thing we have to remember is it’s a mutable array, that means we can change the existing array variables at any time based our need.
  • Syntax:
  • My_list=[] #its an empty array,square bracket denotes it’s a list.
  • Now let’s see some of the important functions under List and where it can be used. There are 2 ways that we can pass the variables in to that list array as follows.

>>a=[1,0,0,’Cool’] #directly assigning values inside the list

>>a # will return the array values

Result:

1,0,0,Cool

  • Another way of passing variables in to an array.

>>a=[]
>>a.append(1) #append is a method under List, which is used to add
values in to the List array
>>a.append(10)
>>a.append(‘learning’)
>>a 


Result:
1,10,learning

  • but by using append(), we can’t insert two or more value at same time, will have to use append for each values to be added in to an array. If you try the following code then you will be getting an error message as below.

>>a.append(1,0)
>>append() takes exactly one argument

Array Indexing:

Index is the position of the values inside an array(works the way same as string). In list we can return part of the array values as below.
>>a=[100,10,11]
>>a[1] # will return value which is there in first index
>>a[-1] #same as string will read last value
>>a[1:]

Result:
10
11
10,11


1. Join:

  • Join is one of the function we often use in array. Used to join the array values by filling the newly joined char or string.

Eg:

>>‘!!’.join(‘abc’)

>>b=list(‘python’)

>>’O’.join(b)

Result:

‘a!!b!!c’

‘pOyOtOhOoOn’

2. Pop:

Used to remove the last element in an array .

>>My_list=[100,90,’Arun’]

>>My_list.pop()

>>My_list

Result:

[100, 90]



3. Remove:

Used to remove the value by looking specific value in an array.

>>My_list=[1,100,’hello’] >>My_list.remove(‘hello’)
>>My_list

Result:

[1,100]

4. Append:
Used to add the new elements in to an array.

>>My_list=[1,100,’hello’] >>My_list.append(‘hellow’)
>>My_list

Result:

[1,100,’hello’,’hellow’]

5.Reverse:
Will reverse the order of elements in an array.

>>My_list.reverse()
Result:
[‘hellow’,’hello’,100,1]

6.Insert:
Will insert the new element in to an array at the the position which we have specified.

>>My_list=[1,100]
>>My_list.insert(‘hi’,1) # will be inserted in 1st position in an array

Result:
[1,’hi’,100]

7.Extend:

Used to concatenate the two different lists.

>>My_list=[1,100]

>>ur_list=[1,1000]

>>My_list.extend(ur_list)

Result:

[1,100,1000]

2. Tuple Array

Its a immutable Array, which means you can’t change or modify the elements in an array once its created.  remember, tuple array always enclosed by round bracket ‘( )’

>> My_tuple=(1,100,2000,90,90)

>>My_tuple

Result:

(1,100,2000,90,90)

Now let’see few important functions from tuple

1. Count():

Will return the count of specified values from array.

>> My_tuple=(1,100,2000,90,90)

>>My_tuple.count(90)

>>My_tuple

Result:

2

Note : If  you want to change the type of an array from one to another, we can do it as follow using type().

>>My_tuple=type(list)

>>My_tuple

Result:

[1,100,2000,90,90]

3. Dictionary {Key:Value}:

Its a mutable array. Values will be stored in key and value format.

>>Empl={} # Empty array

>>Empl[‘name’] = ‘Raj’,’Ram’ # value Raj and Ram will be stored under the Key value Name

>>Empl

Result:

{‘name’:(‘Raj’,’Ram’)}

To display the content of an array:

>>Empl.items()

To display the key values alone from array:

>>Empl.keys()

4.Set

Its a mutable array. Doesn’t support indexing and allows only unique will be stored in an array.

>>my_set={1,100,200}

>>set[1]  # remember  set doesn’t support indexing so it will throw an error.

Now let see some commonly used functions.

1. Intersection:

Used to return the common values from two different set.

>>my_set = {1,100,110}

>>my_set1={0,100,1222}

>>my_set intersection(my_set1)

Result:

100

All other remaining functions are more or less same as list array functions and similar syntax.

OPERANDS

Same as other programming languages, python has many operands for mathematical and conditional statements . 

= , =! (not equal) , > , <, ==(comparison) , >= ,<=  etc

LOOPS 

As most of us already aware, there are certain things we cannot separate from programming , in that one most important thing is loops. Here are some examples for your recap.

Note: When you are using loops, you should be more careful about the indentation error 

IF: 

# prime no

n = int(raw_input(“Please enter an integer:” ))

for i in range(n):

    if i%2 <> 0:

        print i

FOR:

#multiplication table

n = int(raw_input(“Please enter an integer:” ))

for i in range(10) :

    print (i+1)*n

WHILE: 

i = int(raw_input(“Please enter an integer:” ))

while(i<=10):

    print i

List Comprehension:

Python simplifies the usage of FOR loop by introducing list comprehension. What is list comprehension? Let’s see one example that can explain it well

a)Normal FOR loop:
>>b=[]
>>a=[‘mango’,’apple’,’banana’]
>>for i in a:
>> b.append(‘fruit_’+i)
>>print b
Result:
[‘fruit_mango’, ‘fruit_apple’, ‘fruit_banana’]

b)List Comprehension:
>>a=[‘mango’,’apple’,’banana’]
>>b=[‘fruit-‘+ i for i in a]
>>b

Result:
[‘fruit_mango’, ‘fruit_apple’, ‘fruit_banana’]

As you notice in above two examples, list comprehension simplified the programming. Instead of creating an empty array and then defining for loop, we can use the for loop condition inside the variable assignment itself- That is the use of list comprehension .

Functions

So far we have seen , lot of predefined functions in python but what if you want some new
function in your program and it should do what you instructed to do , for that we have some
features in python.

Syntax:
>>def function name():
>>lines of codes…
>>…………..
>>return

Examples:
a)
>>def myfn():
>>a=5*9
>>return ‘Here is the value of a’
>>print a
>>myfn()# calling the function
Result:
45
‘Here is the value of a’

b)
>>def myfn1():
>>a=5*9
>>print ‘got it’ # things which declared after return wont be considered in function.
>>return a
>>myfn1() #calling the function

Result:
45

CONCLUSION

What ever we covered here is just the brief introduction about the high level basic
concepts in python that will be used in upcoming data science and machine learning package as well. In the upcoming post we will discuss more about data science packages like numpy, 
pandas , matplotlib  etc

 

 

 



One thought on “Basics Of Python For Data Science”

Leave a Reply