List Symbol | [] |
Create List | List1 = [val1, val2, val3, …] |
Print List | List1 = [val1, val2, val3, …]
print (List1) |
Change List Elements | List1[2] = “Lisa”
print(List1) #It prints [val1, val2, “Lisa”, …] |
Access Subjects in List | List1 = [val1, val2, “Lisa”, …]
List1[1] # val2
print(List1) |
Append List: | List1 = [val1, val2, “Lisa”, …]
List1.append([v1, v2, v3]) # changes original, adds 1 value, a list |
Extend List: | List1 = [val1, val2, “Lisa”, …]
List1.extend([v1, v2, v3]) # changes original adds 3 values |
Key list information | Heterogeneous e.g., mixed_string = [1, 2, 6, 7.9, “hi”, [25, “ships”]]
Zero-based
Slice list l1[start:end: step] #element at stop not included. All of them are optional |
Tuples Symbol | () |
2 ways of creating a tuple | t1 = 2, 3, 4 # defines a tuple - immutable
t2 = (5, 6, "days", -.5) # defines another tuple |
Print Tuple | print (t1)
print(t2) |
Change Tuples Elements | can't change Elements in tuples |
Access Subjects in Tuples | t1[2] |
Key Tuples Information: | Similar to lists
Values cannot be changed
Declared using ( ) e.g. t1 = (“a”, “b”, “c”) or no delimiter e.g. t2 = 1, 2, 3
Convenient for returning multiple values from a function |
Dictionaries Symbol | {} |
Create Dictionaries | commodities = {"corn":3.46 , "wheat": 4.40 , "soybeans" : 9.3}
OR
myComm = commodities.get("barley", 8.5) # assigns 8.50 |
Access key dictionaries | print(commodities.keys("wheat")) #4.40 |
Access Value Dictionaries: | print(commodities.values(9.3)) #Soybeans |
Add Key:Value: | commodities["quinoa"] = 10.3 # adds another key:value pair |
Key Dictionaries Information: | Unordered set of pairs
Associates values with keys
Get/Set value by key (explicit or implicit)
Check for key existence |
Sets symbol | {} |
create set | rainbow = {"red", "orange", "yellow", "green", 7, "blue", "indigo", [“pink”, “orange”],"violet"}
# may have mixed types but not mutable types like lists, sets, dict
theColors = rainbow |
Set add | theColors.add("brown") #add an item
theColors.add(“yellow”) #no change, already there |
Set.update(): | theColors.update(["black", "white", "purple“]) #add multiple |
Key Sets Information: | Unordered
Unindexed
No duplicates
Use loop structure to traverse
Use ‘in’ to search |
Numpy Symbol | .np |
Create Numpy | import numpy as np # Add the NumPy module with alias
aName0 = np.array(25) #create a 0_d array
aName = np.array([1,2,3,4,5,6,7,8]) # create a 1-D numpy array. Made up of 0-D arrays
aName2 = np.array([[1,2,3,4],[5,6,7,8]]) # create a 2-D array. Made up of 1-D arrays |
print numpy | print(aName[6])
print(aName2)
print(aName2[1,3]) |
np.arrange: | np.arange(start, stop, step)
Will not include the value stop.
Default start is 0
Default step is 1 |
Key Numpy Information: | faster than lists |
Function Format | def fname(parameters): # default values may be assigned to parameters
“”” description “””
Statements
return result |
Number 10 function | def cube_Num_or_10(theNumber = 10):
return theNumber * theNumber * theNumber
print(cube_Num_or_10(5), cube_Num_or_10()) |
If Statements(excute code conditionally): | if condition:
---- Statements # note the indentation to define the scope |
Elif Statements: | if condition1:
--------statements1
elif condition2: # more that one elif section allowed
--------statements2 |
Else Statements: | if condition1:
------statements1
elif condition2: # 0 or more elif sections allowed
-------statements2
else: # if all prior options are false
--------statements3 |
Nested Statement | If condition:
----statements1
if condition2 #nested if
------statements2
else:
------statements3 |
Example of If Statement Used for Temperture: | temp = 60
if temp > 85 :
------print ("temp is {}, scorching summer day" .format(temp))
elif temp > 65 :
------print ("temp is {}, comfortable summer day" .format(temp))
elif temp >45 :
-------print ("temp is {}, summer must be leaving" .format(temp))
else :
-------print ("temp is {}, feels like winter" .format(temp)) |
While Statement(excute code repeatly): | while condition:
-------Statements #at least one statement must make condition false
else:
------statements #execute when condition becomes false
break # to exit loop while condition still true
continue # to exit iteration |
Example of While loop with num: | # WHILE construct
num = 11
while num > 0:
----num -=1
---- if num % 4 == 0:
------- #skip 0 and multiples of 4
------- print("skip multiples of 4") continue
-----print(num)
-----print("looping's over") |
For loop else statement: | for var in sequence:
-----statements
else:
-----statements2 #execute once on exiting loop |
For loop nest statement: | for var1 in sequence1:
---- for var2 in sequence2: #nested loop
-----------statements |
For loop variable: | for var in range(start, end, inc) #default start is 0, inc is 1 statements #execute
-------Statements fixed number of times |
Example of for loop with studennts: | # FOR loop
students = ["john","jean", "juan" , "johan"]
for person in students:
---print (person) |
Example of for loop using range: | for evenNum in range(2,30, 2):
----print(evenNum) |
Example of for loop using random number: | import random
teamAges = []
for x in range (15):
-----teamAges.append (random.randint (10 ,25))
print (teamAges |
List Compresion Key Information: | -Transform a list into another list
-Choose elements
- Transform elements
-Result is a list |
List Compresion Format: | newStruct= transform list 1
i.e.
newStruct = [result for value in collection filter] |
Minor List Compression Example: | teamAges = [12,13,14,15,16,17,18,19,20,21,22,23,24,25]
minors = [age for age in teamAges if age <18]
print(minors) |
List Compression Random Numbers: | teamAges = [random.randint(10,25) for _ in range(15)]
print(teamAges) |
Key information on creat and call user function: | May not return anything
Argument same number as parameters
May be assignment to variable
May be arguments to others
Parameter referenced by mutables,vale(inmutable) |
Little Function Example calling it; | def myLilFunction(message="Beautiful day, eh?"):
------print(message)
myLilFunction() #call function using default
myLilFunction("Gorgeous day") #print this message |
Key information on function Arguments Args: | Must be same in number as parameters.
Use * before parameter name for arbitrary number of arguments (*args)
Arguments passed as a collection ( tuple). Use [] to copy to a list |
Key information on keyword argument Args: | Argument's passed using keyword = value pairs
Use ** before parameter name for arbitrary number of arguments (**kwargs)
Arguments passed as a collection (dictionary) |
Example of Function with arbitrary parameter: | Their |
Panda Key information | A module with tools for working with data. Remember NumPy, another module? •
Must be added – import panda as pd •
Think DataFrame
-2D structure Data, column names, row indices |
Create Data Frame: | my_df2 = pd.DataFrame({'Store':["NY1", "NY2",“NY3"], "Age":[10, 8, 5], "Employees":[3, 6, 5], "profit":[100, 189, 127]})
# optional columns= [list of column names], index = [list of indices] to order columns or specify indices |
Passing a list of argument to Data Frame: | my_df3 =pd.DataFrame( [['NY1', 10, 3, 100], ['NY2', 8, 3, 189], ['NY3', 5, 5, 100]],
index = ['a', 'b', 'c’],columns= ['Store', 'Age', 'Employees', ' Profit']) |
Counting Subjects: | bg_df['Gender'].count()
bg_df.Gender.count() #Same as above |
Average Age: | bg_df['Age'].mean() |
Male Statements: | bg_df[bg_df.Gender=="M"].count() |
Average Male statement: | bg_df[bg_df.Gender=="M"].Age.mean() |
Groupby Key information: | to group data and perform aggregate functions on the groups within the data
-Note the non-numeric columns are omitted from sum(), mean(), … with numeric_only = True
-Grouping may be done by columns (axis=1) e.g. using data types • Multilevel grouping (using multiple values is also possible e.g. by StoreState, StoreType |
Groupby Example: | here |
Groupby Aggregate: | bg_df.groupby('Gender').Age.agg(['mean', 'max', 'min', 'median']) |
Groupby Example: | df.groupby(‘StoreState’) -groups them by state
df.groupby(‘StoreState’).sum(), -groups the state and find the sum of all categories |