Download presentation
Presentation is loading. Please wait.
1
Python workshop Marc Tavenier –
2
Contents Why use Python in our field? The basics
Working with Excel data Plotting How to use Google if you’re stuck 2 practical assignment Python workshop
3
Why use Python in our field?
1/24/2020 Why use Python in our field? Way more versatile The number 2 most popular programming language (behind JavaScript, which is way more difficult for beginners) Completely free Platform-agnostic What are we aiming to substitute? Python is better than Excel, R and Matlab at dealing with tabular data. Python workshop
4
Getting started – the basics
Environment Language Control Flow Organizing Libraries Python workshop
5
Environment Anaconda Navigator Spyder Python workshop 1/24/2020
Anaconda = toolset for data scientists Spyder = one of those tools that is a scientific python development environment Python workshop
6
56 3 1003 56.1 3.001 TRUE FALSE ”Richard Mollier” [1, 2, 3, “Richard”]
1/24/2020 Language Booleans Integers = ℤ Floats = ℝ Strings Lists Tuples TRUE FALSE ”Richard Mollier” [1, 2, 3, “Richard”] (1, 2, 3, “Richard”) Lists = mutable; can be modified after creation Tuples = immutable; can not be modified after creation. Usually lists are the better way to go. Python workshop
7
1/24/2020 Control Flow “ IF my master project is not complete within one year, choose another study.” if master_project is not complete: choose_another_study = True elif study_duration > 10: #years just_quit = True else: print("You're winning in life") Does anyone know what type of variable complete is? Python workshop
8
Iterate over a sequence (list, tuple, string, etc.)
1/24/2020 Control Flow “ FOR … ” Iterate over a sequence (list, tuple, string, etc.) chairs = ["Performance", "Materials", "Lighting"] for chair in chairs: print(chair) Using the ‘for-loop’ we can iterate over a sequence. A sequence can be a list, a tuple, a string, etc. Python workshop
9
Execute a set of statements as long as a condition is True
1/24/2020 Control Flow “ WHILE … ” Execute a set of statements as long as a condition is True i = 1 while i < 5: print(i) i = i + 1 With the while loop we can execute a set of statements as long as a condition is True. Do make sure that the condition will turn True at some point, or you have yourself an infinite loop. i += 1 Python workshop
10
Organizing def function_1(x, y): # insert plot script here
1/24/2020 Organizing def function_1(x, y): # insert plot script here function_1(x=1, y=2) ””” leave a slightly longer message for your future self chairs = ["Performance", "Materials"] for chair in chairs: print(chair) # leave a message for your future self # chairs = ["Performance", "Materials"] for chair in chairs: print(chair) Line comments Block comments Function definition def function_2(x, y): z = x * y return z z = function_2(x=1, y=2) Python workshop
11
Libraries Pandas Numpy Matplotlib Communication with Excel
1/24/2020 Libraries Pandas Communication with Excel Data management: Alignment Reshaping Pivoting Merging Numpy MATLAB-like operations that can be done on arrays or matrices Nd-array: n-dimensional array / data structure Matplotlib MATLAB-like plotting library Python workshop
12
Working with Excel data
1/24/2020 Working with Excel data import pandas as pd df = pd.read_excel('file.xlsx', sheet_name='Data’) mean_value = df.mean() min_value = df.min() max_value = df.max() print(mean_value) print(min_value) print(max_value) Python workshop
13
Plotting Plots you can’t (easily) make with Excel: Boxplots
1/24/2020 Plotting Plots you can’t (easily) make with Excel: Boxplots Violin plots Scatter plots filtered via colour/marker size Contour plots Vector plots Heatmaps Polar plots Etc. Python workshop
14
1/24/2020 Plotting import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) plt.ylabel('some numbers’) plt.show() Smallest code example Python workshop
15
How to Google What not to do: What to do instead:
1/24/2020 How to Google What not to do: “ My plot won’t plot why ” What to do instead: Try the cheat sheets if you’re a beginner Include “Python” in the search to make sure you’re not looking at a different language Use proper terminology Copy paste the Python error, click search and watch the magic happen. Conclusion and jokes for the lulz Python workshop
16
Practical assignment Time to whip out your laptops! Assignment 1:
1/24/2020 Practical assignment Time to whip out your laptops! Assignment 1: Use energy.xlsx to create a correlation matrix Tips: Calculate the correlations with Pandas Use the matshow function from Matplotlib Python workshop
17
Practical assignment import matplotlib.pyplot as plt
How I did it: import matplotlib.pyplot as plt import pandas as pd df = pd.read_excel('energy.xlsx') corr = df.corr() plt.matshow(corr) plt.show() Python workshop
18
Practical assignment Time to whip out your laptops! Assignment 2:
1/24/2020 Practical assignment Time to whip out your laptops! Assignment 2: Use co2.xlsx to create a boxplot or violin plot per measurement Make it a plot usable for a report, so don’t forget the necessary labels Python workshop
19
Practical assignment How I did it: import pandas as pd
import matplotlib.pyplot as plt # load Excel df = pd.read_excel('co2.xlsx', header=0) # create figure fig, ax = plt.subplots() # transpose data df = df.T # make boxplot ax.boxplot(df) # style boxplot ax.set_title('$CO_2$ measurements’) ax.set_ylabel('$CO_2$ concentration (ppm)’) # show plot plt.show() Practical assignment How I did it: Python workshop
20
Practical assignment Assignment 3: Use pv.xlsx to create an RMSE plot
1/24/2020 Practical assignment Assignment 3: Use pv.xlsx to create an RMSE plot Make it a plot usable for a report, so don’t forget the necessary labels Bonus points if you add an x=y line Super bonus points if you add a color bar Python workshop
21
Practical assignment How I did it: Python workshop
22
import matplotlib.pyplot as plt # import Excel
import pandas as pd import matplotlib.pyplot as plt # import Excel df = pd.read_excel('pv.xlsx', header=0, index_col=0) # get values from DataFrame meas = df['Measurement’] sim = df['Simulation’] days = df.index.values # make plot fig, ax = plt.subplots() ax.scatter(x=meas, y=sim, c=days) # style plot ax.set_title('RMSE plot’) ax.set_xlabel('Measured irradiance ($Wh/m^2$)’) ax.set_ylabel('Simulated irradiance ($Wh/m^2$)’) ax.set_xlim(left=0, right=9000) ax.set_ylim(bottom=0, top=9000) ax.plot([0, 1], [0, 1], transform=ax.transAxes, zorder=0, color='gray') Python workshop
23
import matplotlib as mpl import numpy as np
# create colorbar import matplotlib as mpl import numpy as np norm = mpl.colors.Normalize(vmin=0, vmax=365) sm = plt.cm.ScalarMappable(norm=norm) sm.set_array([]) cbar = plt.colorbar(sm, ticks=np.linspace(0, 360, 10), boundaries=np.arange(0, 365, 1)) cbar.ax.set_ylabel('Day of the year', rotation=-90, va='bottom’) # show plot plt.show() Python workshop
24
Thanks for joining! Marc Tavenier –
25
1/24/2020 Useful resources Matplotlib example gallery: More on Python basics: The scripts of today The handed-out cheat sheets Python workshop
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.