Вы находитесь на странице: 1из 62

Introduction to Python Workshop

Logan Halstrom
October 05, 2017
Outline
Installation
Sublime Text 3
Anaconda
Python Setup

Running Python
Ipython
Python Fundamentals
Loops
Loading Data and Plotting
Logical Operators
Functions
Dictionaries
Loading Data and Pandas

Logan Halstrom October 05, 2017 2


Installation Sublime Text 3
Download and Install Sublime Text
Editor for scripts
Scripts are text files containing Python code
Editors provide syntax coloring, advanced editing features, etc.
You can use any editor for Python (we’ll use Sublime Text)
Download And Install
Download link: https://www.sublimetext.com/3
Run download and follow installation instructions
Open by searching for “Sublime Text” from Start Menu
(Windows) or Spotlight (macOS)

Sublime Text 3 syntax coloring example from script “Example.py”


Logan Halstrom October 05, 2017 3
Installation Anaconda
Download Anaconda Installer
Anaconda: An All-In-One Python Manager
Easy graphical installation
Install/update packages (collections of pre-defined functions)
Automatically installs Python and important modules

Download Graphical Installer


Download link: https://www.continuum.io/downloads
Choose appropriate Operating System, Python 3.6

Logan Halstrom October 05, 2017 4


Installation Anaconda
Installing Anaconda
Note: The following instructions are forWindows installation. For installation on
macOS, follow the default installation instructions.

1. Locate and run downloaded installation file


(e.g. “Anaconda3-5.0.0-Windows-x86 64.exe”)

2. Click ‘Next’

Logan Halstrom October 05, 2017 5


Installation Anaconda
Installing Anaconda
3. Select ‘I Agree’ to agree to user agreement

Logan Halstrom October 05, 2017 6


Installation Anaconda
Installing Anaconda
4. Select ‘Just Me’ for installation type

Logan Halstrom October 05, 2017 7


Installation Anaconda
Installing Anaconda
5. Select installation location
5a. Default location is user directory (left image)
5b. If user name has spaces, install on C drive (right image)

6. Select ’Next’ to continue

Logan Halstrom October 05, 2017 8


Installation Anaconda
Installing Anaconda
7. Choose default installation options
7a. Do not add Anaconda to path

8. Select ’Install’ to continue

Logan Halstrom October 05, 2017 9


Installation Anaconda
Installing Anaconda
9. Wait for installation to finish

Logan Halstrom October 05, 2017 10


Installation Anaconda
Installing Anaconda
10. Uncheck ‘Learn More’ options
11. Select ‘Finish’ to complete installation

Logan Halstrom October 05, 2017 11


Installation Python Setup
Use Anaconda to Manage Python
Purpose of Anaconda
Install Python and associated packages
Update Python and packages when new versions are released
Many other functions...
Use Anaconda in Command Line
On Windows:
Open ‘Anaconda Prompt’ by searching or from start
menu
Start → All Programs → Anaconda3 (64-bit) →
Anaconda prompt
(Opens a Command Prompt that knows where Python is)
On macOS:
Open ‘Terminal’ by searching
Terminal already knows where Python is
Logan Halstrom October 05, 2017 12
Installation Python Setup
Update Python
Note: The following procedure is required infrequently (as new updates are made
available) so will only need to be done one time for the duration of this course

1. Update Anaconda before updating anything else (if already up


to date, no changes will be made)
1a. Open ‘Anaconda Prompt’ (Windows) or ‘Terminal’
(macOS)
1b. Type ‘conda update conda’ and press ‘Enter’/’return’
2. Update Python to latest version
2a. Type ‘conda update python’
3. Install desired packages
3a. Anaconda has already installed the packages we need:
numpy, matplotlib, scipy, pandas, seaborn
3b. As an example, attempt to install ‘pandas’:
3c. Type ‘conda install pandas’
4. Update packages to latest version
4a. Type ‘conda update pandas’
Logan Halstrom October 05, 2017 13
Installation Python Setup
List of Anaconda Commands
Show all installed packages:
conda list
Search if package called “packagename” is available to install:
conda search packagename
Install package called “packagename”:
conda install packagename
Update a package to its latest version (do this periodically):
conda update packagename
Update Anaconda itself to maintain the latest version:
conda update conda

Logan Halstrom October 05, 2017 14


Running Python Ipython
Use Ipython to Run Python Code and Scripts
Two ways to run Python code
1. Real-time, interactive code/results in command line
2. Run code stored in text file (script) from command line

Python commands issued in IPython (purple) followed by their corresponding output

Logan Halstrom October 05, 2017 15


Running Python Ipython
ListStart
of Ipython
IPython:
Commands (More Commands Here)
ipython
Show path to current directory (what folder you’re in):
pwd
List all files and folders in current directory:
ls
Navigate to directory “newdir” with path “path/to/newdir”:
cd path/to/newdir
Navigate up one level in path:
cd ..
Make a new directory “newdirname” (folder) in current path:
mkdir newdirname
Run Python script “script.py” (must be in directory as script):
run script.py
Exit IPython back into terminal:
exit
Logan Halstrom October 05, 2017 16
Running Python Ipython
Starting Ipython and Navigation
1. Start ipython in ‘Anaconda Prompt’ or ‘Terminal’
1a. Type ‘ipython’ and press ‘Enter’/’return’
1b. Starts interactive Python command line environment
2. Show path to current location (aka ‘folder’ aka ‘directory’)
2a. Type ‘pwd’ (“Print Working Directory”)
3. Show all files in current folder
3a. Type ‘ls’
4. Make new folder to save work in
4a. Move to user folder ‘cd ∼’ (‘Change Directory’ to home)
4b. To make new folder here, type ‘mkdir eae127’
4c. Makes folder called ‘eae127’ (Spaces not recommended)
4. Move to new folder
4b. Type ‘cd eae127’
Protip: To autocomplete a file or folder name in command line, start typing the name,
then press ‘tab’ (Tab Completion)
Logan Halstrom October 05, 2017 17
Running Python Ipython
Command Line Vs Scripting
“Hello World” Example
Hello World in Command Line
1. In ipython, type ‘print(’hello world’)’ and press
‘Enter’/’return’
2. Output is text “hello world”
Hello World in Python Script
1. Open Sublime Text 3 (or other text editor)
2. Save new Python script as “hello.py”
2a. File → Save As
2b. Navigate to save location (e.g. ‘eae127’ folder)
2c. Enter file name, save
3. Type ‘print(’hello world’)’ in Sublime Text and save
4. Type ‘run hello.py’ in ipython
5. Output text is “hello world”, just as before

Logan Halstrom October 05, 2017 18


Running Python Python Fundamentals
Variables
Python Variables
Variables are containers of information
Python variables are created as they are assigned (like Matlab)
Note: Python variables are case-sensitive

Python variable types are implied and can be changed


To make a variable ‘x’ equal to integer ‘5’, type the following
code in ipython (exclude the comments denoted by ‘#’:
10 x = 5 #variable type is implied (this is an integer)
11 print(x)
Now make ‘x’ equal to a floating point value, type in ipython:
14 x = 5.5 #x is now a float, previous value is forgotten
15 print(x)

code from ‘variables.py’

Logan Halstrom October 05, 2017 19


Running Python Python Fundamentals
Mathematical Operations
Now that we can assign variables, let’s do some math!
Perform basic mathematical operations in ipython
Addition: Add 3 to x, assign to y, and print result
10 x = 5 #Assign x a value
11 y = x + 3 #Add 3 to that value and assign to y
12 print('y = {}'.format(y)) #Print value of y
‘format’ allows control over print statements
Other basic math operations:
13 y = x - 5 #Subtraction
14 y = x * 5 #Multiplication
15 y = x / 5 #Division
16 y = x ** 5 #Power ('^' in Matlab)
17 y = x ** (1/3) #Cube root
Hint: Press ‘Up Arrow’ to access previous ipython commands
and call Line 12 after each operation to see the result
code from ‘operations.py’

Logan Halstrom October 05, 2017 20


Running Python Python Fundamentals
Importing Modules
Import Modules (Packages) To Use Pre-Existing Functions
Import modules at beginning of every new script or ipython
session using import
Call functions from module using “module.function” syntax
10 import numpy #Import "numpy" module with "import"
11 numpy.sqrt(25) #Square-root of 25 with numpy functions
12 numpy.cos(numpy.pi) #Cosine of pi using numpy
Built-in functions do not need to be imported (e.g. import)

Simplify Imports with Aliases


Give modules an alias using as
15 import numpy as np #Math function module
16 np.sqrt(25) #square root from numpy using alias np
17 np.cos(np.pi) #cosine and pi with numpy alias
Same syntax as before, with “np” substituted for “numpy”
code from ‘importing.py’

Logan Halstrom October 05, 2017 21


Running Python Python Fundamentals
Lists
List Indexing
Individual items in lists are accessed by their index
Python uses zero-based numbering
List indices start at zero, not one like Matlab
9 #Indexing a list (NOTE: square brackets)
10 x = [1, 2, 3, 4, 5] #Defining a list
11 print(x) #Print all values stored in x
12 print(x[0]) #1st value of x

List Subsets
Get subset of a list by entering a range of indices
Indexing syntax: [start:end+1]
Range from left index up to but not including right index
13 print(x[0:2]) #1st and 2nd values =[1,2] (subtract 1 from last index)
14 print(x[:-2]) #1st thru 3rd from last values =[1,2,3] (zero implied)
15 print(x[1:]) #2nd thru last values =[2,3,4,5] (last index implied)

Logan Halstrom
code from ‘lists.py’ October 05, 2017 22
Running Python Python Fundamentals
Lists
Assigning List Elements
Assign an index a new value using ‘=’
18 #List index assignment
19 x[1] = 10 #2nd item of x now 10 instead of 2 (x=[1,10,3,4,5])

Lists of Different Types


Individual items in lists can be different types
22 #List of different types
23 x = [1, 'two', ['a', 'b', 'c']] #list of integer, string, and list
24 print(x[1]) #output is "two"
25 print(x[2][1]) #output is "b" (indexing a list within a list)
x now contains three different data types
Item 3 is a list, making x a multi-dimensional list
First bracket “[2]” (Line 24) accesses interior list
Second bracket “[1]” accesses “b” from interior list
code from ‘lists.py’

Logan Halstrom October 05, 2017 23


Running Python Python Fundamentals
Numpy Arrays
Numpy Arrays Are Structured Lists
Similar in function to lists, but more constraints
Allows manipulation by numpy functions, reliable, efficient
29 x = np.array( [1, 2, 3, 4, 5] ) #Defining a numpy array
30 print(x[0]) #1st value of x =1 (same as lists)
Multi-dimensional numpy arrays accessed differently than lists
32 x = np.array( [[1, 2], [3, 4]] ) #2D numpy array
33 print(x) #Print entire matrix
34 print(x[1,1]) #=4, Multi-dim. indexing in one bracket (like Matlab)
Single bracket, two dimensions
Numpy array applications will be explored later
code from ‘lists.py’

Logan Halstrom October 05, 2017 24


Running Python Loops
Basic For Loop
Use loops to modify each element of a list or array

1. Start Sublime Text


2. Save script ‘loops.py’ in desired location
3. Make ‘x’ Numpy array with values 1 through 5
4. Use a loop to print each value of x to screen
5. End loop and print all values at once
6. Save script (‘ctrl+S’)
7. Run in ipython ‘run loops.py’
10 x = [1, 2, 3, 4, 5]
11 #Simplest Python For Loop
12 for p in x: #p is placeholder for each item in x (can be any name)
13 print('new loop')
14 print('x[i]={}'.format(p)) #Print current list item using pointer p
15 print(x) #Print whole list (end indentation to end loop)

Note: loop started/ended by indentation


code from ‘loops.py’

Logan Halstrom October 05, 2017 25


Running Python Loops
For Loop with Indexing
8. Comment out previous code except:
10 x = [1, 2, 3, 4, 5]

Note: Toggle comment in Sublime with ‘ctrl + /’ (Windows), ‘cmd + /’ (macOS)


9. Use ‘i’ to loop through all indices of ‘x’ (‘len’ is length of x)
10. Print ‘i’ to screen at each loop
11. Print current value of ’x’ to screen at each loop
12. Save script and run in ipython ‘run loops.py’

17 #Same For Loop with Indexing


18 for i in range(0, len(x)): #Step through indices 0 to len(x)-1
19 print('new loop')
20 print('i={}'.format(i)) #Print current index (0-4)
21 print('x[i]={}'.format(x[i])) #Print current list item (1-5)

code from ‘loops.py’

Logan Halstrom October 05, 2017 26


Running Python Loops
For Loop with enumerate Index Counter
13. Comment out previous code except:
10 x = [1, 2, 3, 4, 5]

14. Loop through ‘x’ values with placeholder ‘p’


15. Count indices with enumerate and ‘i’
16. Add 1 to each element of ‘x’ and print list at end
17. Save script and run in ipython ‘run loops.py’
23 #Use enumeration to count index, add 1 to each value of x
24 for i, p in enumerate(x):
25 print('new loop')
26 print('i={}'.format(i)) #Print current index (0-4)
27 print('x[i]={}'.format(p)) #Print current list item (1-5)
28 x[i] = p + 1 #Adds 1 to value of p, assigns to current element of x
29 print(x) #Prints [2, 3, 4, 5, 6]

code from ‘loops.py’

Logan Halstrom October 05, 2017 27


Running Python Loops
For Loop with Two Lists
18. Comment out previous code except:
10 x = [1, 2, 3, 4, 5]

19. Make additional list ‘y’


20. Use ‘zip’ to loop through multiple lists
21. Use ‘p,q’ as placeholders for current elements of ‘x,y’
22. Save script and run in ipython ‘run loops.py’
31 #Loop through two lists
32 y = [6, 7, 8, 9, 10] #new list
33 for p, q in zip(x, y): #packs lists together
34 print('new loop')
35 print('x[i]={}'.format(p)) #Print current list item (1-5)
36 print('y[i]={}'.format(q)) #Print current list item (6-10)

code from ‘loops.py’

Logan Halstrom October 05, 2017 28


Running Python Loops
Loop Example: Manipulating Data Sets
Use function imports and loops to make and plot data for these
curves:
y1 (x) = 2x + 1
y2 (x) = 20 sin(x) + 25
y3 (x) = 4x
1. Start Sublime Text
2. Save script ‘InClass Loops.py’ in desired location
3. Import modules (Lines 9-10)
4. Make ‘x’ variable ranging from 0 to 100 with 100 points
9 import numpy as np
10 import matplotlib.pyplot as plt
11
12 x = np.linspace(0, 100, 100) #make vector from 0 to 100 with 100 points

code from “InClass Loops.py”

Logan Halstrom October 05, 2017 29


Running Python Loops
Loop Example: Manipulating Data Sets
5. Calculate ‘y1’ (y1 (x) = 2x + 1) using indexing only
9 import numpy as np
10 import matplotlib.pyplot as plt
11
12 x = np.linspace(0, 100, 100) #make vector from 0 to 100 with 100 points
13 #Equation for a Line (indexing loop)
14 y1 = np.zeros(len(x)) #make array of zeros same size as x
15 for i in range(len(x)):
16 y1[i] = 2 * x[i] + 1

code from “InClass Loops.py”

Logan Halstrom October 05, 2017 30


Running Python Loops
Loop Example: Manipulating Data Sets
6. Calculate ‘y2’ (y2 (x) = 20 sin(x) + 25) using ‘enumerate’
9 import numpy as np
10 import matplotlib.pyplot as plt
11
12 x = np.linspace(0, 100, 100) #make vector from 0 to 100 with 100 points
13 #Equation for a Line (indexing loop)
14 y1 = np.zeros(len(x)) #make array of zeros same size as x
15 for i in range(len(x)):
16 y1[i] = 2 * x[i] + 1
17 #Equation for sinusoid (enumeration)
18 y2 = np.zeros(len(x)) #make array of zeros same size as x
19 for i, p in enumerate(x):
20 y2[i] = 20 * np.sin(p) + 25

code from “InClass Loops.py”

Logan Halstrom October 05, 2017 31


Running Python Loops
Loop Example: Manipulating Data Sets
7. Calculate ‘y3’ (y3 (x) = 4x) using Numpy arrays
9 import numpy as np
10 import matplotlib.pyplot as plt
11
12 x = np.linspace(0, 100, 100) #make vector from 0 to 100 with 100 points
13 #Equation for a Line (indexing loop)
14 y1 = np.zeros(len(x)) #make array of zeros same size as x
15 for i in range(len(x)):
16 y1[i] = 2 * x[i] + 1
17 #Equation for sinusoid (enumeration)
18 y2 = np.zeros(len(x)) #make array of zeros same size as x
19 for i, p in enumerate(x):
20 y2[i] = 20 * np.sin(p) + 25
21 #Equation for a third line (no loop using numpy)
22 y3 = 4 * x

code from “InClass Loops.py”

Logan Halstrom October 05, 2017 32


Running Python Loops
Loop Example: Manipulating Data Sets
8. Plot all data sets together
9 import numpy as np
10 import matplotlib.pyplot as plt
11
12 x = np.linspace(0, 100, 100) #make vector from 0 to 100 with 100 points
13 #Equation for a Line (indexing loop)
14 y1 = np.zeros(len(x)) #make array of zeros same size as x
15 for i in range(len(x)):
16 y1[i] = 2 * x[i] + 1
17 #Equation for sinusoid (enumeration)
18 y2 = np.zeros(len(x)) #make array of zeros same size as x
19 for i, p in enumerate(x):
20 y2[i] = 20 * np.sin(p) + 25
21 #Equation for a third line (no loop using numpy)
22 y3 = 4 * x
23 #Basic Plot
24 plt.plot(x, y1)
25 plt.plot(x, y2)
26 plt.plot(x, y3)
27 plt.show()

9. Run in ipython ‘run InClass Loops.py’


code from “InClass Loops.py”
Logan Halstrom October 05, 2017 33
Running Python Loading Data and Plotting
Creating and Saving Data to File
It is often useful or necessary to save data to file for later use
A few examples:
Save experimental data for later analysis
Save computational results for later post-processing
Save data for later use by another individual
Many data saving/loading functions exist. Today we will use
Numpy’s ‘savetxt’ and ‘loadtxt’

Logan Halstrom October 05, 2017 34


Running Python Loading Data and Plotting
Creating and Saving Data to File
Exercise: Make data for a parabola, rotate data by 90o , and plot
both results
1. Start a new script in Sublime Text
2. Save script ‘makedata.py’ in desired location
3. Import Numpy
4. Make ‘x’ Numpy array with values from -5 to 5
11 import numpy as np
12
13 #MAKE ORIGINAL PARABOLA DATA
14 #x is vector aranged from -5 to 5 with 101 points using numpy.linspace
15 x = np.linspace(-5, 5, 101) #Numpy array

code from ‘makedata.py’

Logan Halstrom October 05, 2017 35


Running Python Loading Data and Plotting
Creating and Saving Data to File
5. Calculate ‘y’ data using for loop and equation for parabola
6. Save each variable to its own text file with ‘savetxt’
11 import numpy as np
12
13 #MAKE ORIGINAL PARABOLA DATA
14 #x is vector aranged from -5 to 5 with 101 points using numpy.linspace
15 x = np.linspace(-5, 5, 101) #Numpy array
16 #loop through x vector and calculate each y (makes a parabola)
17 y = np.zeros(len(x)) #Initialize y, same length as x, filled with zeros
18 for i, p in enumerate(x):
19 y[i] = p ** 2 #assign value to current index of y
20 #Save original data to text file
21 np.savetxt('x.dat', x) #file name, data to save
22 np.savetxt('y.dat', y)

code from ‘makedata.py’

Logan Halstrom October 05, 2017 36


Running Python Loading Data and Plotting
Creating and Saving Data to File
7. Set angle of rotation θ (in radians)
8. Calculate rotated data (‘prime’) with 2D rotation equation
11 import numpy as np
12
13 #MAKE ORIGINAL PARABOLA DATA
14 #x is vector aranged from -5 to 5 with 101 points using numpy.linspace
15 x = np.linspace(-5, 5, 101) #Numpy array
16 #loop through x vector and calculate each y (makes a parabola)
17 y = np.zeros(len(x)) #Initialize y, same length as x, filled with zeros
18 for i, p in enumerate(x):
19 y[i] = p ** 2 #assign value to current index of y
20 #Save original data to text file
21 np.savetxt('x.dat', x) #file name, data to save
22 np.savetxt('y.dat', y)
23
24 #ROTATE DATA
25 #basic 2D rotation, see: https://en.wikipedia.org/wiki/Rotation_matrix
26 theta = -90 * np.pi / 180 #Rotaion angle (radians)
27 #Use Numpy implied loop to calculate rotated data
28 xprime = x * np.cos(theta) - y * np.sin(theta)
29 yprime = x * np.sin(theta) + y * np.cos(theta)
code from ‘makedata.py’

Logan Halstrom October 05, 2017 37


Running Python Loading Data and Plotting
Creating and Saving Data to File
9. Save rotated data to individual files
11 import numpy as np
12
13 #MAKE ORIGINAL PARABOLA DATA
14 #x is vector aranged from -5 to 5 with 101 points using numpy.linspace
15 x = np.linspace(-5, 5, 101) #Numpy array
16 #loop through x vector and calculate each y (makes a parabola)
17 y = np.zeros(len(x)) #Initialize y, same length as x, filled with zeros
18 for i, p in enumerate(x):
19 y[i] = p ** 2 #assign value to current index of y
20 #Save original data to text file
21 np.savetxt('x.dat', x) #file name, data to save
22 np.savetxt('y.dat', y)
23
24 #ROTATE DATA
25 #basic 2D rotation, see: https://en.wikipedia.org/wiki/Rotation_matrix
26 theta = -90 * np.pi / 180 #Rotaion angle (radians)
27 #Use Numpy implied loop to calculate rotated data
28 xprime = x * np.cos(theta) - y * np.sin(theta)
29 yprime = x * np.sin(theta) + y * np.cos(theta)
30 #Save transformed data to file
31 np.savetxt('xprime.dat', xprime)
32 np.savetxt('yprime.dat', yprime)
code from ‘makedata.py’
Logan Halstrom October 05, 2017 38
Running Python Loading Data and Plotting
Loading Data and Plotting
Start an new script for plotting with default settings at
beginning
Below is “boilerplate” code you can copy/paste at the
beginning of every script
Contains default plotting settings such as font sizes

1. Start a new script in Sublime Text


2. Save script ‘plotdata.py’ in desired location
3. Copy/paste “boilerplate” into script (see next slide)

Logan Halstrom October 05, 2017 39


Running Python Loading Data and Plotting
Loading Data and Plotting
11 #STANDARD BOILERPLATE:
12 import numpy as np
13 import matplotlib.pyplot as plt
14 #SET DEFAULT FONT SIZES
15 params = {
16 'axes.labelsize' : 32, #Axis Labels
17 'axes.titlesize' : 32, #Title
18 'font.size' : 28, #Textbox
19 'xtick.labelsize': 22, #Axis tick labels
20 'ytick.labelsize': 22, #Axis tick labels
21 'font.family': 'helvetica' #Font family
22 }
23 import matplotlib
24 matplotlib.rcParams.update(params)
25 #SET DEFAULT FIGURE APPERANCE
26 import seaborn as sns #Fancy plotting package
27 #No Background fill, legend font scale, frame on legend
28 sns.set(style='whitegrid', font_scale=1.5, rc={'legend.frameon': True})
29 #Mark ticks with border on all four sides (overrides 'whitegrid')
30 sns.set_style('ticks')
31 #ticks point in
32 sns.set_style({"xtick.direction": "in","ytick.direction": "in"})
33 #fix invisible marker bug
34 sns.set_context(rc={'lines.markeredgewidth': 0.1})
35 ### END OF BOILERPLATE##################################################
Logan Halstrom October 05, 2017 40
Running Python Loading Data and Plotting
Loading Data and Plotting
4. Load all datasets from file
5. Make string for title of figure and set title
6. Set x/y axis labels
38 #LOAD DATA FROM FILE
39 xorig = np.loadtxt('x.dat')
40 yorig = np.loadtxt('y.dat')
41 xprime = np.loadtxt('xprime.dat')
42 yprime = np.loadtxt('yprime.dat')
43
44 #PLOT DATA
45 #Start Figure
46 plt.figure()
47 #Title of Figure ($$ is LaTeX math notation)
48 title = 'Coordinate Rotation by $-90^o$'
49 plt.title(title) #Set figure title
50 plt.xlabel("x, x'") #Set X-axis label
51 plt.ylabel("y, y'") #Set Y-axis label

code from ‘plotdata.py’

Logan Halstrom October 05, 2017 41


Running Python Loading Data and Plotting
Loading Data and Plotting
7. Plot original parabola (notice line continuation)
44 #PLOT DATA
45 #Start Figure
46 plt.figure()
47 #Title of Figure ($$ is LaTeX math notation)
48 title = 'Coordinate Rotation by $-90^o$'
49 plt.title(title) #Set figure title
50 plt.xlabel("x, x'") #Set X-axis label
51 plt.ylabel("y, y'") #Set Y-axis label
52 #Plot Original Data
53 #Legend label is 'Original', color is red, linestyle is dashed, no marker
54 plt.plot(xorig, yorig, label='Original', color='red', linestyle='--',
55 linewidth=1.5)

code from ‘plotdata.py’

Logan Halstrom October 05, 2017 42


Running Python Loading Data and Plotting
Loading Data and Plotting
8. Plot rotated parabola with different appearance
44 #PLOT DATA
45 #Start Figure
46 plt.figure()
47 #Title of Figure ($$ is LaTeX math notation)
48 title = 'Coordinate Rotation by $-90^o$'
49 plt.title(title) #Set figure title
50 plt.xlabel("x, x'") #Set X-axis label
51 plt.ylabel("y, y'") #Set Y-axis label
52 #Plot Original Data
53 #Legend label is 'Original', color is red, linestyle is dashed, no marker
54 plt.plot(xorig, yorig, label='Original', color='red', linestyle='--',
55 linewidth=1.5)
56 #Plot Transformed Data
57 #Label is 'Transformed', color is blue, linestyle is solid, 'x' markers
58 plt.plot(xprime, yprime, label='Transformed', color='blue',
59 linestyle='-', linewidth=1.5,
60 marker='o', markersize=8)

code from ‘plotdata.py’

Logan Halstrom October 05, 2017 43


Running Python Loading Data and Plotting
Loading Data and Plotting
9. Make legend for describing data sets
44 #PLOT DATA
45 #Start Figure
46 plt.figure()
47 #Title of Figure ($$ is LaTeX math notation)
48 title = 'Coordinate Rotation by $-90^o$'
49 plt.title(title) #Set figure title
50 plt.xlabel("x, x'") #Set X-axis label
51 plt.ylabel("y, y'") #Set Y-axis label
52 #Plot Original Data
53 #Legend label is 'Original', color is red, linestyle is dashed, no marker
54 plt.plot(xorig, yorig, label='Original', color='red', linestyle='--',
55 linewidth=1.5)
56 #Plot Transformed Data
57 #Label is 'Transformed', color is blue, linestyle is solid, 'x' markers
58 plt.plot(xprime, yprime, label='Transformed', color='blue',
59 linestyle='-', linewidth=1.5,
60 marker='o', markersize=8)
61 #Plot Legend located in 'best' space
62 plt.legend(loc='best')
code from ‘plotdata.py’

Logan Halstrom October 05, 2017 44


Running Python Loading Data and Plotting
Loading Data and Plotting
10. Save and show figure
44 #PLOT DATA
45 #Start Figure
46 plt.figure()
47 #Title of Figure ($$ is LaTeX math notation)
48 title = 'Coordinate Rotation by $-90^o$'
49 plt.title(title) #Set figure title
50 plt.xlabel("x, x'") #Set X-axis label
51 plt.ylabel("y, y'") #Set Y-axis label
52 #Plot Original Data
53 #Legend label is 'Original', color is red, linestyle is dashed, no marker
54 plt.plot(xorig, yorig, label='Original', color='red', linestyle='--',
55 linewidth=1.5)
56 #Plot Transformed Data
57 #Label is 'Transformed', color is blue, linestyle is solid, 'x' markers
58 plt.plot(xprime, yprime, label='Transformed', color='blue',
59 linestyle='-', linewidth=1.5,
60 marker='o', markersize=8)
61 #Plot Legend located in 'best' space
62 plt.legend(loc='best')
63 #Save Figure. File extension (i.e. '.png', '.pdf') will set filetype
64 plt.savefig('Rotation.png', bbox_inches='tight')
65 plt.show() #Optional, show the plot as you run the code
code from ‘plotdata.py’

Logan Halstrom October 05, 2017 45


Running Python Logical Operators
Logic Syntax
1. Open an Anaconda Prompt or macOS Terminal
2. Enter ipython environment by typing ’ipython’
3. Assign ‘x’ boolean value ‘True’
4. Evaluate if ‘x’ is True
10 #If statement with boolean
11 x = True
12 if x == True:
13 print('x is true!')

5. The same evaluation can be made implicitly


14 #Same if statement, comparison implied
15 if x:
16 print('x is true!')

code from ‘if.py’

Logan Halstrom October 05, 2017 46


Running Python Logical Operators
Logic Syntax
6. 1 can also be used as the boolean True
17 #Same if statement, 1 is also boolean true
18 x = 1
19 if x:
20 print('x is true!')

7. ‘False’ (and 0) are Python’s boolean False


21 #'False' and '0' are boolean false
22 x = False
23 if not x:
24 print('x is false!')

code from ‘if.py’

Logan Halstrom October 05, 2017 47


Running Python Logical Operators
Logic Syntax
8. Additional comparison operators include ‘<=’, ‘>=’, ’! =’
9. Multiple comparisons can be made at once with ‘and’ and ‘or’
26 x = 5 #define x
27 y = 'str' #define y
28 #Conditional operators:
29 x > 2 #true (Greater-than comparison)
30 x == 2 #false (Equality comparison)
31 x >= 5 and y == 'notstr' #false (and condition)
32 x >= 5 or y == 'notstr' #true (or condition)
33 x >= 5 and y != 'notstr' #true (Non-equality comparison)

code from ‘if.py’

Logan Halstrom October 05, 2017 48


Running Python Logical Operators
Logic Flow Control
10. Use ‘elif’ to evaluate additional, successive comparisons
11. Use ‘else’ as catch-all option if all above evaluate as false
35 #Multiple if conditions (no "then" required)
36 if x > 5: #if statement
37 print('x is greater than five')
38 elif x == 5: #else if statement
39 print('x is equal to five')
40 else: #else statement (needs no condition)
41 print('x is less than five')

code from ‘if.py’

Logan Halstrom October 05, 2017 49


Running Python Functions
Function Definition and Usage
Functions
Use functions for processes repeated many times
You have already used pre-made functions (e.g. ‘cos’, ‘sqrt’)
Functions can be defined in scripts and in the command line
1. Start a new script in Sublime Text
2. Save script ‘functions.py’ in desired location
3. Import Numpy
4. Define function with ‘def’
5. All indented code will run any time the function is called
6. Call function any time after definition with its name
9 import numpy as np
10
11 #Function Definition Example
12 def sayhi():
13 """Print 'hello world' when called. No function inputs."""
14 print("Hello World")
15 sayhi() #Calls function 'sayhi', prints 'hello world'
code from ‘functions.py’
Logan Halstrom October 05, 2017 50
Running Python Functions
Function With Input
7. Define function with inputs contained in parentheses
8. New and old function can both be called in a loop
11 #Function Definition Example
12 def sayhi():
13 """Print 'hello world' when called. No function inputs."""
14 print("Hello World")
15 sayhi() #Calls function 'sayhi', prints 'hello world'
16
17 def sayinput(text):
18 """Print provided input to screen"""
19 print(text)
20 for i in range(10):
21 sayhi()
22 sayinput(i)

code from ‘functions.py’

Logan Halstrom October 05, 2017 51


Running Python Functions
Function with Output
9. Return variables from a function with ‘return’
24 #Function With Inputs
25 def power(x, y):
26 """Return the value of input x to the power of input y"""
27 return x ** y
28
29 number = 2
30 exponent = 3
31 outvar = power(number, exponent) #assign output to 'outvar'
32 print( '{}^{}={}'.format(number, exponent, outvar) ) #output: "2^3=8"

code from ‘functions.py’

Logan Halstrom October 05, 2017 52


Running Python Functions
Functions In Loops
10. Functions can be called multiple times to square each list
element
34 #Function in loop (Square all values of L)
35 L = [1, 2, 3, 4, 5]
36 for i, l in enumerate(L):
37 L[i] = power(l, 2) #square each list element)
38 print('Result of function call in loop:', L) #output: "[1, 4, 9, 16, 25]"

11. Numpy allows element-wise application of functions


40 #Element-wise function execution with Numpy array (square all values of L)
41 L = np.array(L) #Change 'L' from list to Numpy array
42 L = power(L, 2) #square all elements at once
43 print('Result of element-wise function call:', L)

code from ‘functions.py’

Logan Halstrom October 05, 2017 53


Running Python Dictionaries
Use Dictionaries As Containers
Dictionaries are like lists where indices are strings
Dictionaries can store any type of variable, just like lists
Use any string to represent a dictionary input (called a “key”)
Allows for easier processing of many similar sets of data

Exercise: Plot data for 3 curves like ‘InClass Loops.py’ and then
rotate the curves like ‘makedata.py’ using dictionaries
1. Start a new script in Sublime Text
2. Save script ‘dictionary.py’ in desired location
3. Perform standard imports
4. Initialize dictionary with curly brackets
10 import numpy as np
11 import matplotlib.pyplot as plt
12
13 dat = {} #Dictionary to store all data sets
code from ‘dictionary.py’

Logan Halstrom October 05, 2017 54


Running Python Dictionaries
Use Dictionaries As Containers
5. Assign a numpy array to dictionary with key ‘x’
6. Assign each curve to same dictionary with different key
7. Print to screen to show dictionary structure
13 dat = {} #Dictionary to store all data sets
14 dat['x'] = np.linspace(0, 100, 100) #store x vector in dict, call with 'x'
15 print(dat)
16 #first curve: y=2x+1
17 dat['y1'] = 2 * dat['x'] + 1 # y1=2*x+1 <-- equivalent code
18 #second curve: y=20sin(x)+25
19 dat['y2'] = 20 * np.sin(dat['x']) + 25
20 #third curve: y=4x
21 dat['y3'] = 4 * dat['x']
22 print(dat)

code from ‘dictionary.py’

Logan Halstrom October 05, 2017 55


Running Python Dictionaries
Perform Operation On Multiple Data Sets In Loop
8. Perform 2D rotation multiple times by defining function
31 #ROTATE ALL DATA SETS
32 def Rotation2D(x, y, theta):
33 """Preforms 2D rotation of x/y by angle theta"""
34 xprime = x * np.cos(theta) - y * np.sin(theta)
35 yprime = x * np.sin(theta) + y * np.cos(theta)
36 return xprime, yprime

code from ‘dictionary.py’

Logan Halstrom October 05, 2017 56


Running Python Dictionaries
Perform Operation On Multiple Data Sets In Loop
9. Initialize new dictionary to store rotated data
10. Define list of keys to call in loop
11. Define rotation angle θ
12. Call rotation function in loop
13. Unique, rotated ‘x’ for each curve requires new key
14. Rotated ‘y’ stored with same key as previous dictionary
38 rot = {} #new dict stores rotated data
39 ykeys = ['y1', 'y2', 'y3'] #list of dictionary keys
40 theta = -90 * np.pi / 180 #angle of rotation
41 #perform all rotation by looping through dict keys
42 for i, ykey in enumerate(ykeys):
43 xp, yp = Rotation2D(dat['x'], dat[ykey], theta)
44 rot['x{}'.format(i+1)] = xp #Rotated x requires unique key (e.g. 'x1')
45 rot[ykey] = yp #save rotated y value to dict with same key as 'dat'
46 print(rot)

code from ‘dictionary.py’

Logan Halstrom October 05, 2017 57


Running Python Dictionaries
Plot Results in Loop
15. Define list of x keys to loop through with y keys
16. Define list of colors to assign to each pair of curves
17. Plot each original and rotated curve in loop
18. Set equal axis scales
19. Show plot when script is run
48 xkeys = ['x1', 'x2', 'x3']
49 colors = ['red', 'blue', 'black']
50 plt.figure()
51 for ykey, xkey, color in zip(ykeys, xkeys, colors):
52 #plot original line
53 plt.plot(dat['x'], dat[ykey], color=color)
54 #plot rotated line
55 plt.plot(rot[xkey], rot[ykey], color=color, linestyle='--')
56 plt.axis('equal')
57 plt.show()

code from ‘dictionary.py’

Logan Halstrom October 05, 2017 58


Running Python Loading Data and Pandas
Pandas Demonstration
Pandas Dataframes are like dictionaries with more functionality
Use similar syntax to call and define values
Automatic features allow for easier data visualization
Built-in functions facilitate data manipulation and file i/o
Features will be demonstrated later, only basic usage in this
example

Logan Halstrom October 05, 2017 59


Running Python Loading Data and Pandas
Pandas Demonstration
20. In ‘dictionary.py’, additionally import ‘pandas’
21. Make dictionary ‘rot’ into pandas DataFrame ‘df’
22. Print first 10 rows of dataframe to screen
23. Save dataframe to space-separated file, with column headers
59 #PANDAS DEMONSTRATION
60 import pandas as pd
61
62 df = pd.DataFrame(rot) #make dictionary 'rot' into pandas dataframe
63 print(df.head()) #'head' command only prints the first few rows
64 #save rotation data to file
65 #'sep' is character separating data (a space in this case)
66 #index=False to avoid extra index column
67 df.to_csv('dfsave.dat', sep=' ', index=False)

24. Open file ‘dfsave.dat’ to see file formatting


code from ‘dictionary.py’

Logan Halstrom October 05, 2017 60


Running Python Loading Data and Pandas
Load Multiple Columns of Data
Load saved data from previous exercise using Numpy and Pandas

1. Start a new script in Sublime Text


2. Save script ‘loaddata.py’ in desired location
3. Load data with Pandas’s ‘read csv’
4. Load Numpy matrix with ‘loadtxt’, skip header row
9 import numpy as np
10 import pandas as pd
11
12 #load saved rotation data
13 df = pd.read_csv('dfsave.dat', sep=' ') #'sep' is character separating data
14 print('pandas:')
15 print(df.head(1)) #print first line of dataframe
16
17 #read same file with numpy
18 out = np.loadtxt('dfsave.dat', skiprows=1)
19 print('numpy:')
20 print(out[0,:]) #print first row of numpy matrix
code from ‘loaddata.py’

Logan Halstrom October 05, 2017 61


Running Python Loading Data and Pandas
Load Multiple Columns of Data
5. Extract ‘x1’ data from Dataframe with key
6. Extract ‘x1’ data from Numpy matrix with row index
22 #Extract x1 data from each container
23 x1pandas = df['x1'] #get x1 data out of pandas dataframe
24 x1numpy = out[:,0] #get x1 data out of numpy matrix
25 print(x1pandas)
26 print(x1numpy)

7. Distribute all data columns to variables with ‘unpack’


28 #Use 'unpack' option to distribute each column to a variable
29 x1, y1, x2, y2, x3, y3 = np.loadtxt('dfsave.dat', skiprows=1, unpack=True)
30 print(x1)

code from ‘loaddata.py’

Logan Halstrom October 05, 2017 62

Вам также может понравиться