0% found this document useful (0 votes)
28 views16 pages

Lab 02 Tools and Techniques For Data Science

Uploaded by

Awais Asghar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views16 pages

Lab 02 Tools and Techniques For Data Science

Uploaded by

Awais Asghar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Lab 02 Tools and techniques for Data Science

October 28, 2022

1 Tools and Techniques for Data Science


1.1 Lab 02: # Introduction to Jupyter notebook, Python objects and Data
structure
PAF-IAST Fall 2022 Lab Instructor: Engr.Awais Asghar Email address: awais.asghar@paf-
iast.edu.pk
In this lecture, we will learn about Objects and Data Structures of Python and how to use them.
We’ll learn about the following topics:
1.) Types of numbers in Python
2.) Variable Assignment and Working with Numbers
3.) Strings
4.) Lists
5.) Dictionaries
6.) Tuple
7.) Sets

1.2 Types of Numbers


Python has various “types” of numbers (numeric literals).
All forms of non-negative numbers including integer number, real number, complex number, hex-
adecimal, binary number and octal number belong to numeric literals.
We’ll mainly focus on integers and floating point numbers.
Integers are just whole numbers, positive or negative. For example: 2 and -2 are examples of
integers.
Floating point numbers in Python are notable because they have a decimal point in them, or use
an exponential (e) to define the number. For example 2.0 and -2.1 are examples of floating point
numbers. 4E2 (4 times 10 to the power of 2) is also an example of a floating point number in
Python.
Here is a table of the two main types we will spend most of our time working with some examples:
Examples
Number “Type”
1,2,-5,1000

1
Integers
1.2,-0.5,2e2,3E2
Floating-point numbers

1.3 Variable Assignment and Working with Numbers


We will start with assigning values to variables. the values can be of “integer” type or “float” type.
Please consider the following rules before naming the variables.
1. Names can not start with a number.
2. There can be no spaces in the name, use _ instead.
3. Can't use any of these symbols :'",<>/?|\()!@#$%^&*~-+
4. It's considered best practice that names are lowercase.
5. Avoid using the characters 'l' (lowercase letter el), 'O' (uppercase letter oh),
or 'I' (uppercase letter eye) as single character variable names.
6. Avoid using words that have special meaning in Python like "list" and "str"
Using variable names can be a very useful way to keep track of different variables in Python. For
example:
[1]: #assigning different number types to different variables
my_income = 100
tax_rate = 0.1

TIP: Use object names to keep better track of what’s going on in your code!
[2]: #performing calculation by using variables
my_taxes = my_income*tax_rate

[3]: # printing the variable


my_taxes

[3]: 10.0

OR
[4]: # printing the variable
print(my_taxes)

10.0

1.3.1 Task 1
Calculate the area of a rectangle having length of 15 cm and width of 10 cm. Use variable assignment
and perform calculations using variables. Also display the result.
[ ]: # Assign values to variables

[ ]: # Perform Calculation

2
[ ]: # Display the result

1.4 Booleans
Python comes with Booleans (with predefined True and False displays that are basically just the
integers 1 and 0). Let’s walk through a few quick examples of Booleans.

[6]: # Set object to be a boolean


a = True

[3]: #Show
a

[3]: True

[4]: 3>2

[4]: True

We can also use comparison operators to create booleans. We will go over all the comparison
operators later on in the course.
[3]: # Output is boolean
1 > 2

[3]: False

1.5 Determining variable type with type()


You can check what type of object is assigned to a variable using Python’s built-in type() function.
Common data types include: * int (for integer) * float * str (for string) * list * tuple * dict (for
dictionary) * set * bool (for Boolean True/False)

[4]: type(4)

[4]: int

[5]: type(3.14)

[5]: float

[6]: int(False)

[6]: 0

[7]: type("True")

[7]: str

3
2 Strings
Strings are used in Python to record text information, such as names. Strings in Python are actually
a sequence, which basically means Python keeps track of every element in the string as a sequence.
For example, Python understands the string ”hello’ to be a sequence of letters in a specific order.
In this lecture we’ll learn about the following:
1.) Creating Strings
2.) Printing Strings

2.1 Creating a String


To create a string in Python you need to use either single quotes or double quotes. For example:
[1]: # Single word
b="hello123"
print(b)

hello123

[2]: # Entire phrase


'This is also a string'

[2]: 'This is also a string'

[3]: # We can also use double quote


"String built with double quotes"

[3]: 'String built with double quotes'

[4]: # what will be the output of this??


'I'm using single quotes, but this will create an error'

File "<ipython-input-4-57a3e764a544>", line 2


'I'm using single quotes, but this will create an error'
^
SyntaxError: invalid syntax

The reason for the error above is because the single quote in I’m stopped the string. You can use
combinations of double and single quotes to get the complete statement.
[5]: "I'm using single quotes, but this will create an error'"

[5]: "I'm using single quotes, but this will create an error'"

4
2.2 Printing a String
Using Jupyter notebook with just a string in a cell will automatically output strings, but the correct
way to display strings in your output is by using a print function.
[6]: # We can simply declare a string
'Hello World'

[6]: 'Hello World'

[7]: # Note that we can't output multiple strings this way


'Hello World 1'
'Hello World 2'

[7]: 'Hello World 2'

We can use a print statement to print a string.


[8]: print('Hello World 1')
print('Hello World 2')
print('Use \n to print a new line')
print('\n')
print('See what I mean?')

Hello World 1
Hello World 2
Use
to print a new line

See what I mean?


We can also assign string to a variable!
[46]: a='Hello World'
a[]

[46]: 'l'

2.3 String Properties


It’s important to note that strings have an important property known as immutability. This means
that once a string is created, the elements within it can not be changed.
Something we can do is concatenate strings!
[10]: s='hello'

[11]: # Concatenate strings!


s + ' concatenate me!'

5
[11]: 'hello concatenate me!'

[12]: # We can reassign s completely though!


s = s + ' concatenate me!'
print(s)

hello concatenate me!


We can use the multiplication symbol to create repetition!
[13]: letter = 'z'

[14]: letter*10

[14]: 'zzzzzzzzzz'

2.3.1 Task 2
Make a string having your name and print it 5 times.
[15]: # string assignment

[16]: # printing the string

3 Lists
Lists can be thought of the most general version of a sequence in Python. Unlike strings, they are
mutable, meaning the elements inside a list can be changed!
In this section we will learn about:
1.) Creating lists
2.) Indexing and Slicing Lists
3.) Nesting Lists
Lists are constructed with brackets [] and commas separating every element in the list.
Let’s go ahead and see how we can construct lists!
[17]: # Assign a list to an variable named my_list
my_list=[1,2,3]

[18]: my_list

[18]: [1, 2, 3]

We just created a list of integers, but lists can actually hold different object types. For example:
[19]: my_list = ['A string',23,100.232,'o']

6
[20]: my_list

[20]: ['A string', 23, 100.232, 'o']

3.0.1 Indexing and Slicing


We know Lists are a sequence, which means Python can use indexes to call parts of the sequence.
Let’s learn how this works.
In Python, we use brackets [] after an object to call its index. We should also note that indexing
starts at 0 for Python.
We can use a : to perform slicing which grabs everything up to a designated point.
Let’s create a new object called my_list and then walk through a few examples of indexing.. Let’s
make a new list to remind ourselves of how this works:
[21]: my_list = ['one','two','three',4,5]

[22]: # Grab element at index 0


my_list[0]

[22]: 'one'

[23]: # Grab index 1 and everything past it


my_list[1:]

[23]: ['two', 'three', 4, 5]

[24]: # Grab everything UP TO index 3


my_list[:3]

[24]: ['one', 'two', 'three']

You can always access the indices in reverse. For example working according to the index, my_list[0]
will be the first item and my_list[-1] will be the last one. Try the fowwlowing code.

[25]: # Grab the last index in reverse


my_list[-1]

[25]: 5

Try yourself!
[35]: # Grab the second last index in reverse

7
3.0.2 Checking the type

[36]: type(my_list)

[36]: list

[37]: # identifying type of specific object in list


type(my_list[4])

[37]: int

3.0.3 Task 3
Suppose we have a list containing areas of different rooms. Complete the given tasks using indexing
and slicing.
[38]: # The list having areas of 6 rooms respectively
area=[28.3, 45.9, 123.4, 555, 213, 121]

[39]: # Show the area of third room in the list

[40]: # Show the areas of rooms first three rooms in the list

[41]: # Show the area of rooms from 2 to 5

We can also use ‘+’ to concatenate lists.


[42]: my_new=my_list + ['new item']

[43]: my_new

[43]: ['one', 'two', 'three', 4, 5, 'new item']

Note: This doesn’t actually change the original list!


[44]: my_list

[44]: ['one', 'two', 'three', 4, 5]

Note that lists are mutable objects i.e. a separate index can be changed through indexing
[45]: #mutable list objects can be changed
my_new[0]= 1
my_new

[45]: [1, 'two', 'three', 4, 5, 'new item']

You would have to reassign the list to make the change permanent.

8
[46]: # Reassign
my_list = my_list + [1]

[47]: my_list

[47]: ['one', 'two', 'three', 4, 5, 1]

We can also use the * for a duplication method similar to strings:


[48]: my_list * 2

[48]: ['one', 'two', 'three', 4, 5, 1, 'one', 'two', 'three', 4, 5, 1]

[49]: my_list*3

[49]: ['one',
'two',
'three',
4,
5,
1,
'one',
'two',
'three',
4,
5,
1,
'one',
'two',
'three',
4,
5,
1]

[50]: # Again doubling not permanent


my_list

[50]: ['one', 'two', 'three', 4, 5, 1]

4 Dictionaries
We’ve been learning about sequences in Python but now we’re going to switch gears and learn about
mappings in Python. If you’re familiar with other languages you can think of these Dictionaries as
hash tables.
This section will serve as a brief introduction to dictionaries and consist of:
1.) Constructing a Dictionary

9
2.) Accessing objects from a dictionary
3.) Nesting Dictionaries
So what are mappings? Mappings are a collection of objects that are stored by a key, unlike a
sequence that stored objects by their relative position. This is an important distinction, since
mappings won’t retain order since they have objects defined by a key.
A Python dictionary consists of a key and then an associated value. That value can be almost any
Python object.

4.1 Constructing a Dictionary


Let’s see how we can construct dictionaries to get a better understanding of how they work!
[2]: # Make a dictionary with {} and : to signify a key and a value
my_dict = {'key1':'value1','key2':'value2'}

[3]: # Call values by their key


my_dict['key2']

[3]: 'value2'

Its important to note that dictionaries are very flexible in the data types they can hold. For
example:
[4]: my_dict = {'key1':123,'key2':[12,23,33],'key3':['item0','item1','item2']}

[5]: # Let's call items from the dictionary


my_dict['key3']

[5]: ['item0', 'item1', 'item2']

[6]: # finding out the type


type(my_dict)

[6]: dict

Task: Check type of ‘key2’


[8]: # Try here!

We can affect the values of a key as well. For instance:


[9]: my_dict['key1']

[9]: 123

[10]: # Subtract 123 from the value


my_dict['key1'] = my_dict['key1'] - 123

10
[11]: #Check
my_dict['key1']

[11]: 0

We can also create keys by assignment. For instance if we started off with an empty dictionary, we
could continually add to it:
[12]: # Create a new dictionary
d = {}

[13]: # Create a new key through assignment


d['animal'] = ['Dog','Cat']

[14]: # Can do this with any object


d['answer'] = 42

[15]: #Show
d

[15]: {'animal': ['Dog', 'Cat'], 'answer': 42}

[16]: # Dictionary nested inside a dictionary nested inside a dictionary


d = {'key1':{'nestkey':{'subnestkey':'value'}}}

[17]: # Keep calling the keys


d['key1']['nestkey']

[17]: {'subnestkey': 'value'}

[18]: d

[18]: {'key1': {'nestkey': {'subnestkey': 'value'}}}

[19]: # for getting the inner most value


d['key1']['nestkey']['subnestkey']

[19]: 'value'

4.2 Dictionaries Exercise


[ ]: # Definition of countries and capital
countries = ['spain', 'france', 'germany', 'norway']
capitals = ['madrid', 'paris', 'berlin', 'oslo']

# From string in countries and capitals, create dictionary europe

11
#print europe

5 Tuples
In Python tuples are very similar to lists, however, unlike lists they are immutable meaning they
can not be changed. You would use tuples to present things that shouldn’t be changed, such as
days of the week, or dates on a calendar.
In this section, we will get a brief overview of the following:
1.) Constructing Tuples
2.) Immutability
3.) When to Use Tuples
You’ll have an intuition of how to use tuples based on what you’ve learned about lists. We can
treat them very similarly with the major distinction being that tuples are immutable.

5.1 Constructing Tuples


The construction of a tuples use () with elements separated by commas. For example:

[27]: # Create a tuple


t = (1,2,3)

[28]: # Can also mix object types


t = ('one',2)

# Show
t

[28]: ('one', 2)

[29]: # Use indexing just like we did in lists


t[0]

[29]: 'one'

[30]: # Slicing just like a list


t[-1]

[30]: 2

5.2 Immutability
It can’t be stressed enough that tuples are immutable. To drive that point home:
[31]: t[0]= 'change' # what will be the output of this?

12
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-31-9ca178c8039b> in <module>
----> 1 t[0]= 'change' # what will be the output of this?

TypeError: 'tuple' object does not support item assignment

Because of this immutability, tuples can’t grow. Once a tuple is made we can not add to it.
[32]: t.append('nope')

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-32-b75f5b09ac19> in <module>
----> 1 t.append('nope')

AttributeError: 'tuple' object has no attribute 'append'

5.3 When to use Tuples


You may be wondering, “Why bother using tuples when they have fewer available methods?” To
be honest, tuples are not used as often as lists in programming, but are used when immutability is
necessary. If in your program you are passing around an object and need to make sure it does not
get changed, then a tuple becomes your solution. It provides a convenient source of data integrity.
You should now be able to create and use tuples in your programming as well as have an under-
standing of their immutability.

6 Sets
Sets are an unordered collection of unique elements. We can construct them by using the set()
function. Let’s go ahead and make a set to see how it works
[26]: x = set()

[27]: type(x)

[27]: set

[28]: # We add to sets with the add() method


x.add(1)

[29]: #Show
x

[29]: {1}

13
Note the curly brackets. This does not indicate a dictionary! Although you can draw analogies as
a set being a dictionary with only keys.
We know that a set has only unique entries. So what happens when we try to add something that
is already in a set?
[30]: # Add a different element
x.add(2)
# show
x

[30]: {1, 2}

[31]: # Try to add the same element


x.add(1)
# show
x

[31]: {1, 2}

Notice how it won’t place another 1 there. That’s because a set is only concerned with unique
elements! We can cast a list with multiple repeat elements to a set to get the unique elements. For
example:
[32]: # Create a list with repeats
list1 = [1,1,2,2,3,4,5,6,1,1]

[33]: # Cast as set to get unique values


set(list1)

[33]: {1, 2, 3, 4, 5, 6}

6.1 Object Type Casting


You can cast type of any object in Python. Common data types casting functions include: * int()
(for integer) * float() * str() (for string) * bool() (for Boolean True/False)
You can type cast any object throught the following code. The given example is converting float
to int.
int(5.8)

7 Task
[33]: # convert 80 into float type,
# convert 20.9 into a string and check its type
# convert a boolean valua into int
# convert '123' into float

14
[34]: float(10)

[34]: 10.0

[35]: a=55.5

[36]: int(a)

[36]: 55

[41]: a=11.5
b=5
r=a%b

[42]: r

[42]: 1.5

8 Tasks
8.0.1 Question#01
a). Create a list with the following elements 1, hello, [1,2,3] and True.
b). Find the value stored at index 1.
c). Retrieve the elements stored at index 1, 2 and 3 of above created list.
d). Concatenate the following lists
A = [1, ‘a’] B = [2, 1, ‘d’]:

8.0.2 Question#02
You will need this dictionary for part a and b: yourname = {“The Bodyguard”:“1992”, “Saturday
Night Fever”:“1977”}
a). In the dictionary soundtrack_dict what are the keys ?
b). In the dictionary soundtrack_dict what are the values ?
The Albums Back in Black, The Bodyguard and Thriller have the following music recording sales
in millions 50, 50 and 65 respectively:
c). Create a dictionary album_sales_dict where the keys are the album name and the sales in
millions are the values.
d). Use the dictionary to find the total sales of Thriller.
e). Find the names of the albums from the dictionary using the method keys.
f). Find the names of the recording sales from the dictionary using the method values.

8.0.3 Question#03
Consider the following tuple:

15
genres_tuple = (“pop”, “rock”, “soul”, “hard rock”, “soft rock”, “R&B”, “progressive rock”,
“disco”)
a). Find the length of the tuple?
b). Access the element, with respect to index 3.
c). Use slicing to obtain indexes 3, 4 and 5.
d). Find the first two elements of the tuple.
e). Find the first index of “disco”.
f). Generate a sorted List from the Tuple C_tuple=(-5, 1, -3).

[ ]:

16

You might also like