10 Python Built-in Functions Which You Should Know While Learning Data Science

10 Python Built-in Functions Which You Should Know While Learning Data Science
10 Python Built-in Functions

There are many inbuilt functions and methods in python. Here are a few of the crucial functions:

1. Replace( ): The replace( ) method creates a replica of the string by replacing every instance of one substring with a different substringIt returns a new string where all the old substrings are replaced with a new substring.

Syntax: string.replace(old, new, count)

Old: old substring that we want to replace

New: old substring will be replaced with this new substring

Count: The number of times we want to replace the old with a new substring

Examples and uses: 

  • ## Replace all ‘two’ with ‘four’

Sample=”one, two, three, one, two, three, one, two, three”

Sample.replace(‘two’, ‘four’)

  • ## Replace only first ‘two’ with ‘four’

Sample=”one, two, three, one, two, three, one, two, three”

Sample.replace(‘two’, ‘four’, 1)

  • Replace function is very helpful in handling missing values in a data frame.

import numpy as np

import pandas as pd   

# will replace  Nan value in dataframe with value 99 

data.replace(to_replace = np.nan, value = 99)

#Replace the null values with the mean: 


df[‘A’].replace([numpy.nan], df[A].mean(), inplace=True)

Refer this article: Support Vector Machine Algorithm (SVM) – Understanding Kernel Trick

2. Map: The map function applies the given function to each item of a given iterable (list, tuple, etc.) 

Syntax: map(function, iterables)

Function: a function that performs some action on each element of an iterable

Iterables: an iterable like sets, lists, tuples, etc

Examples and uses: 

  • ## Program to add number with itself

def addition(n):

    return n + n

numbers = (1, 2, 3, 4)

result = map(addition, numbers)

list(result)

  • ## To add two different numbers (we can pass multiple iterables also)

def addition(n1,n2):

    return n1 + n2

n1 = (1, 2, 3, 4)

n2=(3,4,6,8)

result = map(addition, n1,n2)

list(result)

  • ## Map with lambda function

num = (1, 2, 3, 4)

result = map(lambda x: x + x, num)

list(result)

  • The map function can be used to change categorical values to numerical values in the data frame.

Read this article: Advantages and Disadvantages of Artificial Intelligence (AI)

3. Format( ): The format function is used to format any string.

Syntax: string.format(value1, value2…)

The format() method formats the specified value(s) and insert them inside the string’s placeholder. The placeholders can be identified using named indexes {name}, numbered indexes {1}, or even empty placeholders {}.

Examples and uses: 

str1 = “My name is {fname}, I’m {age}”.format(fname = “Jack”, age = 20)
str2 = “My name is {0}, I’m {1}”.format(“Jack”,20)
str3 = “My name is {}, I’m {}”.format(“Jack”,20)

Refer to the article: What is a Gradient Descent?

4. Apply ( ): Apply function can be treated as an alternative to loops in data frames and series. It applies a function on each element in a pandas Series and each row or column in a pandas DataFrame.

          Syntax: s.apply(function, convert_dtype=True, args=())

Function: Function to apply to each column or row.

s: series/Dataframe

Examples and uses: 

Also read this article: Exploratory Data Analysis

5. Filter: This function  verifies whether each element in the series is true or false, 

Syntax: filter(function, sequence)

  function: function that tests if each element of a sequence is true or not.

sequence: sequence like sets, lists, tuples, or containers of any iterators.

Examples and uses:

  • ## Program to return the ages that are greater than 18

ages = [6, 13, 16, 19, 25, 33]

def age(x):

   if x < 18:

    return False

    else:

     return True

adults = filter(age, ages)

for x in adults:

   print(x)

Pythagorean Triplet program using Python

6. Range: It is used to return a sequence of numbers.

Syntax: range(start, stop, step)

Start: The integer number specifying with which number to start. By default, it is 0.

Stop: The integer number specifying the last number.

Step: An integer number specifying the incrementation. By default, it is 1.

Examples and uses: 

  • ## printing numbers from 3 to 20 with increments of 2

for i in range(3,20,2):

     print(i, end=” “)

                        output: 3 5 7 9 11 13 15 17 19 

  • ## performing sum of natural number

sum = 0

for i in range(1, 11):

    sum = sum + i

print(“Sum of first 10 natural number :”, sum)

           Output: Sum of first 10 natural numbers: 55

Python vs Java – What Is The Difference

7. Isinstance( ): This function returns True if the object is specified types, and it will not match then return False.

         Syntax: isinstance(obj, class)

Examples and uses: 

numbers = [1, 2, 3]

result = isinstance(numbers, list)

print(numbers,’instance of list?’, result)

           Output: [1, 2, 3] instance of list? True

What is HR analytics?

8. Any and All

Any Returns True if any of the items is True and returns False if empty or all are false. It can be thought of as – a sequence of OR operations.

Syntax: any(iterable)

Examples and uses: 

  • print (all([True, True, True, True]))

            print (all([False, True, True, False]))

               output: True

             False

  • ## It can be used to replace loops

for element in some_iterable:

    if element:

        return True

return False

The above code can be written as:

print(any([2 == 2, 3 == 2]))

print(any([True, False, False]))

print(any([False, False]))

                        output: True

                 True

                 False

All: It can be thought of as – a sequence of And operations. It returns True if all of the items are True.

Syntax: all(iterable)

Examples and uses: 

  • print (all([True, True, True, True]))

  print (all([False, True, True, False]))

                    Output: True

                False

  • ## Can be used in place of loops

for element in iterable:

    if not element:

        return False

return True

The above code can be written as:

                print(all([2 == 2, 3 == 2]))

                print(all([2 > 1, 3 != 4]))

                print(all([True, False, False]))

    print(all([False, False]))

Python vs SAS – What is the Difference?

9. Zip ( ): The zip() function in Python creates a single iterator object that contains the mapped values from different containers. It is used to map the index of several containers so that a single entity can access all of them.

Syntax: zip(iterator1, iterator2, iterator3 …)

Examples and uses: 

  • a = (“John”, “Charles”, “Mike”)

b = (“Jenny”, “Christy”, “Monica”, “Vicky”)

x = zip(a, b)

print(tuple(x))

output: ((‘John’, ‘Jenny’), (‘Charles’, ‘Christy’), (‘Mike’, ‘Monica’))

10. Append: The Python List append() method is used for adding elements to the end of the List. 

Syntax: list.append(item)

Examples and uses: 

a = [“apple”, “banana”, “cherry”]
b = [“Ford”, “BMW”, “Volvo”]
a.append(b)

output: [‘apple’, ‘banana’, ‘cherry’, [‘Ford’, ‘BMW’, ‘Volvo’]]

Being a prominent data science institute, DataMites provides specialized training in topics including ,artificial intelligence, deep learning, machine learning training, the internet of things and data analytics. Our python course at DataMites have been authorized by the International Association for Business Analytics Certification (IABAC), a body with a strong reputation and high appreciation in the analytics field.