100% found this document useful (1 vote)
187 views9 pages

Python Crash Course

This document provides an overview and examples of key Python concepts like data types, control flow, functions and modules like NumPy, Matplotlib, Pandas. It demonstrates string, number and boolean basics. Loops and conditionals are shown. Lists, tuples and dictionaries are covered as data structures. NumPy examples show arrays, accessing data and arithmetic. Matplotlib creates line and scatter plots. Pandas introduces Series and DataFrames for labeled, multi-dimensional data. Overall, the document teaches Python fundamentals and introduces major libraries used for machine learning.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
100% found this document useful (1 vote)
187 views9 pages

Python Crash Course

This document provides an overview and examples of key Python concepts like data types, control flow, functions and modules like NumPy, Matplotlib, Pandas. It demonstrates string, number and boolean basics. Loops and conditionals are shown. Lists, tuples and dictionaries are covered as data structures. NumPy examples show arrays, accessing data and arithmetic. Matplotlib creates line and scatter plots. Pandas introduces Series and DataFrames for labeled, multi-dimensional data. Overall, the document teaches Python fundamentals and introduces major libraries used for machine learning.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 9

Assignment

As a programmer, assignment and types should not be surprising to you.

Strings

1# Strings
2data = 'hello world'
3print(data[0])
4print(len(data))
5print(data)
Running the example prints:

1h
211
3hello world
Numbers

1# Numbers
2value = 123.1
3print(value)
4value = 10
5print(value)
Running the example prints:

1123.1
210
Boolean

1# Boolean
2a = True
3b = False
4print(a, b)
Running the example prints:

1(True, False)
Multiple Assignment

1# Multiple Assignment
2a, b, c = 1, 2, 3
3print(a, b, c)
Running the example prints:

1(1, 2, 3)
No Value

1# No value
2a = None
3print(a)
Running the example prints:

1None
Flow Control
There are three main types of flow control that you need to learn:
If-Then-Else conditions, For-Loops and While-Loops.

If-Then-Else Condition Example

1value = 99
2if value >= 99:
3print('That is fast')
4elif value > 200:
5print('That is too fast')
6else:
7print('That that is safe')
Running this example prints:

1That is fast
For-Loop Example

1# For-Loop
2for i in range(10):
3print(i)
Running this example prints:

10
21
32
43
54
65
76
87
98
109
While-Loop Example

1# While-Loop
2i = 0
3while i < 10:
4print(i)
5i += 1
Running this example prints:

10
21
32
43
54
65
76
87
98
109
Data Structures
There are three data structures in Python that you will find the most
used and useful. They are tuples, lists and dictionaries.

Tuple Example
Tuples are read-only collections of items.

1a = (1, 2, 3)
2print(a)
Running the example prints:

1(1, 2, 3)
List Example
Lists use the square bracket notation and can be index using array
notation.

1mylist = [1, 2, 3]
2print("Zeroth Value: %d" % mylist[0])
3mylist.append(4)
4print("List Length: %d" % len(mylist))
5for value in mylist:
6print(value)
Running the example prints:

1Zeroth Value: 1
2List Length: 4
31
42
53
64
Dictionary Example
Dictionaries are mappings of names to values, like a map. Note the use
of the curly bracket notation.

1mydict = {'a': 1, 'b': 2, 'c': 3}


2print("A value: %d" % mydict['a'])
3mydict['a'] = 11
4print("A value: %d" % mydict['a'])
5print("Keys: %s" % mydict.keys())
6print("Values: %s" % mydict.values())
7for key in mydict.keys():
8print(mydict[key])
Running the example prints:
1A value: 1
2A value: 11
3Keys: ['a', 'c', 'b']
4Values: [11, 3, 2]
511
63
72
Functions
The biggest gotcha with Python is the whitespace. Ensure that you have
an empty new line after indented code.

The example below defines a new function to calculate the sum of two values
and calls the function with two arguments.

1# Sum function
2def mysum(x, y):
3return x + y
4
5# Test sum function
6print(mysum(1, 3))
Running the example prints:

14

NumPy Crash Course


NumPy provides the foundation data structures and operations for SciPy.
These are arrays (ndarrays) that are efficient to define and manipulate.

Create Array

1# define an array
2import numpy
3mylist = [1, 2, 3]
4myarray = numpy.array(mylist)
5print(myarray)
6print(myarray.shape)
Running the example prints:

1[1 2 3]
2(3,)
Access Data
Array notation and ranges can be used to efficiently access data in a
NumPy array.

1 # access values
2 import numpy
3 mylist = [[1, 2, 3], [3, 4, 5]]
4 myarray = numpy.array(mylist)
5 print(myarray)
6 print(myarray.shape)
7 print("First row: %s" % myarray[0])
8 print("Last row: %s" % myarray[-1])
9 print("Specific row and col: %s" % myarray[0, 2])
10print("Whole col: %s" % myarray[:, 2])
Running the example prints:

1[[1 2 3]
2[3 4 5]]
3(2, 3)
4First row: [1 2 3]
5Last row: [3 4 5]
6Specific row and col: 3
7Whole col: [3 5]
Arithmetic
NumPy arrays can be used directly in arithmetic.

1# arithmetic
2import numpy
3myarray1 = numpy.array([2, 2, 2])
4myarray2 = numpy.array([3, 3, 3])
5print("Addition: %s" % (myarray1 + myarray2))
6print("Multiplication: %s" % (myarray1 * myarray2))
Running the example prints:

1Addition: [5 5 5]
2Multiplication: [6 6 6]
There is a lot more to NumPy arrays but these examples give you a flavor
of the efficiencies they provide when working with lots of numerical data.

Matplotlib Crash Course


Matplotlib can be used for creating plots and charts.

The library is generally used as follows:

1. Call a plotting function with some data (e.g. plot()).


2. Call many functions to setup the properties of the plot (e.g. labels
and colors).
3. Make the plot visible (e.g. show()).
Line Plot
The example below creates a simple line plot from one-dimensional data.

1# basic line plot


2import matplotlib.pyplot as plt
3import numpy
4myarray = numpy.array([1, 2, 3])
5plt.plot(myarray)
6plt.xlabel('some x axis')
7plt.ylabel('some y axis')
8plt.show()
Running the example produces:

Simple Line Plot in Matplotlib

Scatter Plot
Below is a simple example of creating a scatter plot from two-dimensional
data.

1# basic scatter plot


2import matplotlib.pyplot as plt
3import numpy
4x = numpy.array([1, 2, 3])
5y = numpy.array([2, 4, 6])
6plt.scatter(x,y)
7plt.xlabel('some x axis')
8plt.ylabel('some y axis')
9plt.show()
Running the example produces:
Simple Scatter Plot in Matplotlib

There are many more plot types and many more properties that can be set
on a plot to configure it.

Pandas Crash Course


Pandas provides data structures and functionality to quickly manipulate
and analyze data. The key to understanding Pandas for machine learning
is understanding the Series and DataFrame data structures.

Series
A series is a one-dimensional array where the rows and columns can be
labeled.

1# series
2import numpy
3import pandas
4myarray = numpy.array([1, 2, 3])
5rownames = ['a', 'b', 'c']
6myseries = pandas.Series(myarray, index=rownames)
7print(myseries)
Running the example prints:
1a 1
2b 2
3c 3
You can access the data in a series like a NumPy array and like dictionary,
for example:

1print(myseries[0])
2print(myseries['a'])
Running the example prints:

11
21
DataFrame
A data frame is a multi-dimensional array where the rows and the columns
can be labeled.

1# dataframe
2import numpy
3import pandas
4myarray = numpy.array([[1, 2, 3], [4, 5, 6]])
5rownames = ['a', 'b']
6colnames = ['one', 'two', 'three']
7mydataframe = pandas.DataFrame(myarray, index=rownames, columns=colnames)
8print(mydataframe)
Running the example prints:

1 one two three


2a 1 2 3
3b 4 5 6
Data can be index using column names.

1print("one column: %s" % mydataframe['one'])


2print("one column: %s" % mydataframe.one)

Running the example prints:

1one column: a 1
2b 4
3
4one column: a 1
5b 4
Summary
You have covered a lot of ground in this post. You discovered basic syntax
and usage of Python and four key Python libraries used for machine
learning:

 NumPy
 Matplotlib
 Pandas
You now know enough syntax and usage information to read and understand
Python code for machine learning and to start creating your own scripts.

You might also like