Practice 1.1 – Python Pandas Cookbook by Alfred Essa

Following Alfred Essa’s Python Pandas Cookbook on YouTube
Different Ways to Construct Series
import pandas as pd
import numpy as np
Using Series Constructor
s1 = pd.Series([463,3,-728,236,32,-773])
s1
0    463
1      3
2   -728
3    236
4     32
5   -773
dtype: int64
type(s1)
pandas.core.series.Series
s1.values
array([ 463,    3, -728,  236,   32, -773], dtype=int64)
type(s1.values)
numpy.ndarray
s1.index
Int64Index([0, 1, 2, 3, 4, 5], dtype='int64')
s1[3]
236

Defining data and index

data1 = [3.5,5,343,9.3,23]
index1 = ['Mon','Tue','Wed','Thur','Fri']

Creating Series

s2 = pd.Series(data1, index = index1)
s2
Mon       3.5
Tue       5.0
Wed     343.0
Thur      9.3
Fri      23.0
dtype: float64
s2[4]
23.0
s2.index
Index([u'Mon', u'Tue', u'Wed', u'Thur', u'Fri'], dtype='object')
s2.name = 'Daily numbers'
s2.index.name = 'Working days'
s2
Working days
Mon               3.5
Tue               5.0
Wed             343.0
Thur              9.3
Fri              23.0
Name: Daily numbers, dtype: float64
Creating Dictionary
dict1 = {'Jan': -7,'Feb': 2,'March': 12,'April': -9,'May': 3,'June': 4}
s3 = pd.Series(dict1)
s3
April    -9
Feb       2
Jan      -7
June      4
March    12
May       3
dtype: int64
Vectorized Operations
s3 * 2
April   -18
Feb       4
Jan     -14
June      8
March    24
May       6
dtype: int64
np.log(s3)
April         NaN
Feb      0.693147
Jan           NaN
June     1.386294
March    2.484907
May      1.098612
dtype: float64
Slicing
s3['Feb':'May']
Feb       2
Jan      -7
June      4
March    12
May       3
dtype: int64
s3[3:5]
June      4
March    12
dtype: int64
Offset value
s3[3] = 54
s3
April    -9
Feb       2
Jan      -7
June     54
March    12
May       3
dtype: int64
s3.median()
2.5
s3.min()
-9
s3.max()
54
s3.cumsum()
April    -9
Feb      -7
Jan     -14
June     40
March    52
May      55
dtype: int64

Making Looping Clearer – enumerate() returns iterators

for i, v in enumerate(s3):
    print i,v
0 -9
1 2
2 -7
3 54
4 12
5 3
new_s3 = [x**2 for x in s3]
new_s3
[81, 4, 49, 2916, 144, 9]
Series using dictionary
s3['Feb']
2
'Feb' in s3
True
Assignment using key
s3['May'] = 45.8
s3
April    -9
Feb       2
Jan      -7
June     54
March    12
May      45
dtype: int64

Looping over dictionary keys and values

for k,v in s3.iteritems():
    print k,v
April -9
Feb 2
Jan -7
June 54
March 12
May 45
Advertisements

Creating a Dictionary in Python

Dictionary is similar to a list. It contains key:value pairs. Here, we will learn about creating and modifying dictionaries.
Creating Dictionary
dictionary_name = {key:value, key:value,…..}

We create a dictionary with colors of jams as keys and fruit names as values.

jam = {'red':'strawberry', 'yellow': 'mango', 'orange':'orange'}
print jam['orange']
print jam['red']

orange
strawberry

Insertion – Here, we add a new key/value pair to the existing dictionary.

jam['blue'] = 'blueberry'

{‘blue’: ‘blueberry’, ‘red’: ‘strawberry’, ‘yellow’: ‘mango’, ‘orange’: ‘orange’}

Deletion – Here, we delete a key/value pair

del jam['orange']
jam

{‘blue’: ‘blueberry’, ‘red’: ‘strawberry’, ‘yellow’: ‘mango’}

Replacing values – We replace value for key ‘red’ from strawberry to cherry.

jam ['red'] = 'cherry'
jam

{‘blue’: ‘blueberry’, ‘red’: ‘cherry’, ‘yellow’: ‘mango’}

Nesting : We nest a new dictionary within an existing dictionary.

 jam['red'] = {'light' : 'cherry', 'dark' : 'strawberry' }

{‘blue’: ‘blueberry’, ‘red’: {‘dark’: ‘strawberry’, ‘light’: ‘cherry’}, ‘yellow’: ‘mango’}
We set a list as a value for key ‘blue’.

jam['blue'] = ['blueberry','plum']
jam

{‘blue’: [‘blueberry’, ‘plum’], ‘red’: {‘dark’: ‘strawberry’, ‘light’: ‘cherry’}, ‘yellow’: ‘mango’}

Append to a list

jam['blue'].append('jamun')  
print jam['blue']

[‘blueberry’, ‘plum’, ‘jamun’]

Indexing the nested dictionary

print jam['red']['dark']

strawberry

jam

{‘blue’: [‘blueberry’, ‘plum’, ‘jamun’], ‘red’: {‘dark’: ‘strawberry’, ‘light’: ‘cherry’}, ‘yellow’: ‘mango’}

Python Lists and Dictionaries

I Lists

i. Introduction to Lists 1/14

zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"];
# One animal is missing!

if len(zoo_animals) > 3:
	print "The first animal at the zoo is the " + zoo_animals[0]
	print "The second animal at the zoo is the " + zoo_animals[1]
	print "The third animal at the zoo is the " + zoo_animals[2]
	print "The fourth animal at the zoo is the " + zoo_animals[3]

ii. Access by Index 2/14

numbers = [5, 6, 7, 8]

print "Adding the numbers at indices 0 and 2..."
print numbers[0] + numbers[2]
print "Adding the numbers at indices 1 and 3..."
print numbers[1] + numbers[3]

iii. New Neighbors 3/14

zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
# Last night our zoo's sloth brutally attacked 
#the poor tiger and ate it whole.

# The ferocious sloth has been replaced by a friendly hyena.
zoo_animals[2] = "hyena"
zoo_animals[3] = "lion"
# What shall fill the void left by our dear departed tiger?
# Your code here!

II List Capabilities and Functions

i. Late Arrivals & List Length 4/14

suitcase = [] 
suitcase.append("sunglasses")

# Your code here!
suitcase.append("doll")
suitcase.append("ball")
suitcase.append("comb")


list_length = len(suitcase) # Set this to the length of suitcase

print "There are %d items in the suitcase." % (list_length)
print suitcase

ii. List Slicing 5/14

suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]

first  = suitcase[0:2]  # The first and second items (index zero and one)
middle = suitcase[2:4]   # Third and fourth items (index two and three)
last   = suitcase[4:6]  # The last two items (index four and five)

iii. Slicing Lists and Strings 6/14

animals = "catdogfrog"
cat  = animals[:3]   # The first three characters of animals
dog  = animals[3:6]          # The fourth through sixth characters
frog = animals[6:10]              # From the seventh character to the end

iv. Maintaining Order 7/14

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck")
# Use index() to find "duck"
animals.insert(duck_index,"cobra")# Your code here!
print animals # Observe what prints after the insert operation

v. For One and All 8/14

my_list = [1,9,3,8,5,7]

for number in my_list:
    print 2*number
      # Your code here

vi. More with ‘for’ 9/14

start_list = [5, 3, 1, 2, 4]
square_list = []

for x in start_list:
    
    square_list.append(x**2)
    square_list.sort()
print square_list

III Dictionaries

i. This Next Part is Key 10/14

# Assigning a dictionary with three key-value pairs to residents:
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}

print residents['Puffin'] # Prints Puffin's room number

print residents['Sloth']
print residents['Burmese Python']
# Your code here!

ii. New Entries 11/14

menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
print menu['Chicken Alfredo']

menu['Mom Alfredo'] = 10.50
menu['Bob Alfredo'] = 13.50
menu['Fish Alfredo'] = 19.50
menu['Lamb Alfredo'] = 17.50 # Your code here: Add some dish-price pairs to menu!

print "There are " + str(len(menu)) + " items on the menu."
print menu

iii. Changing Your Mind 12/14

# key - animal_name : value - location 
zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}
# A dictionary (or list) declaration may break across multiple lines

# Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.)
del zoo_animals['Unicorn']
del zoo_animals['Sloth']
del zoo_animals['Bengal Tiger']
zoo_animals['Rockhopper Penguin'] = 'Antarctic Exhibit'

# Your code here!
print zoo_animals

iv. Remove a Few Things 13/14

backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']
backpack.remove('dagger')

v. It’s Dangerous to Go Alone! Take This 14/14

inventory = {
    'gold' : 500,
    'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
    'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}

# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']
inventory['pocket'] = ['seashell','strange berry','lint']

# Sorting the list found under the key 'pouch'
inventory['pouch'].sort() 
inventory['backpack'].sort()
inventory['backpack'].remove('dagger')
inventory['gold'] = 550