This is an old revision of the document!
Table of Contents
Data wrangling in Python
https://jorisvandenbossche.github.io/FLAMES-python-data-wrangling/
Cours donné par Stijn Van Hoey et Joris Vanden Bossche les 25/11 et 02/12/2024 à l'Université de Gand :
Day 0 : préparation
Après avoir installé Anaconda, vérifier qu'il est à jour : ouvrir une console :
conda update -n base conda
il faut activer l'environnement pour le cours : dans Anaconda, après l'avoir installé
conda activate FLAMES-python Télécharger le fichier pour préciser l'environnement : <code>wget https://raw.githubusercontent.com/jorisvandenbossche/FLAMES-python-data-wrangling/main/environment.yml
qui contient :
name: FLAMES-python channels: - conda-forge dependencies: - python=3.11 - ipython - jupyter - jupyterlab>=3 - numpy - pandas>=1 - matplotlib>3 - mplleaflet - ipympl - seaborn - plotnine - pyproj - requests - openpyxl
Ensuite, dans Anaconda : base (root) > Terminal :
conda install -n base conda-libmamba-solver conda config --set solver libmamba conda config --add channels conda-forge conda config --set channel_priority strict cd FOLDER_PATH_TO_ENVIRONMENT_FILE conda env create -f environment.yml
où FOLDER_PATH_TO_ENVIRONMENT_FILE = là on on a téléchargé environment.yml précédemment. Ensuite, taper :
conda activate FLAMES-python ipython
pour ouvrir un terminal python où taper :
import pandas import matplotlib
Day 1
git clone https://github.com/jorisvandenbossche/FLAMES-python-data-wrangling.git cd FLAMES-python-data-wrangling conda activate FLAMES-python python check_environment.py conda activate FLAMES-python jupyter lab
Ne pas fermer cette fenêtre. Une fenêtre du browser s'ouvre, sélectionner dans l'explorateur 'Notebooks', c'est là que le cours se trouve.
- pour créer une nouvelle fenêtre dans laquelle écrire du code : cliquer sur une fenêtre existente, appuyer sur la touche “Escape” et ensuite sur la touche “b”
- pour faire tourner du code, cliquer sur la fenêtre (pour y avoir le curseur), ensuite shift + touche “Return”
Pandas
dataframe : object with rows and columns
Each column in a dataframe is a series.
data = {'country': ['Belgium', 'France', 'Germany', 'Netherlands', 'United Kingdom'], 'population': [11.3, 64.3, 81.3, 16.9, 64.9], 'area': [30510, 671308, 357050, 41526, 244820], 'capital': ['Brussels', 'Paris', 'Berlin', 'Amsterdam', 'London']} countries = pd.DataFrame(data) countries
Liste des variables :
countries.columns
2 premiers/derniers rows:
countries.head(2) countries.bottom(2)
tri :
countries.sort_values("population")
graphique (2e et 3e lignes = pareil) :
countries.plot() countries["population"].plot(kind="box") countries["population"].plot.box()
import data :
pd.read_csv
export data : method of dataframe object
countries.to_excel
Exercice 1
import pandas as pd # importer les données dans un dataframe df=pd.read_csv("data/titanic.csv") # 5 premières lignes df.head(5) # nombre de records len(df) df.shape[0] # select Age column df['Age'] # make a boxplot of Age df.plot.bot('Age') # sort by age desc df.sort_values("Age", ascending=False) df.sort_values(by="Age", ascending=False)
Exercice 2
#Import pandas as pd and read the Titanic dataset df=pd.read_csv("data/titanic.csv") # what is the average age of the passengers? df['Age'].mean() # Plot the age distribution of the titanic passengers df['Age'].plot.hist() # What is the survival rate? (the relative number of people that survived) df['Survived'].sum() / len(df['Survived']) df['Survived'].mean() # What is the maximum Fare? And the median? df['Fare'].max() df['Fare'].median() # Calculate the 75th percentile (quantile) of the Fare price help(df.quantile) df['Fare'].quantile(0.75) df.quantile(0.75, numeric_only=True) # Calculate the scaled Fares (scaled relative to its mean), and add this as a new column ('Fare_scaled') to the DataFrame df['Fare_scaled'] = df['Fare'] / df['Fare'].mean() # Calculate the log of the Fares import numpy as np fare_log = np.log(df['Fare']) print(fare_log)
“Magics” : pas dans Python, mais dans l'environnement des notebooks (commencent par '%')
#liste des variables définies %whos a = np.arange(1000) %timeit a**2
Subsetting data
# select columns: countries[['area', 'population']] # double [[]]
Double crochets parce qu'on a une liste dans [] #select rows: mask = countries['population'] > 50 mask countries[mask] countries[0:100:10] # 1er, 11e, 21e…</code>
Conditions (return True or False = boolean)
- ==, !=, <, >=
- & (and), | (or)
.isin() operator = between 2 boundaries
→ boolean mask
to select data:
data_filtered = data[boolean_mask]
countries['country'] == "Belgium" countries['country'].isin(["Belgium", "France"]) capital = countries['capital'] capital == "Brussels" s = "Brussels" s.startwith("A") s.startwith("B") capital.str.startwith("B")
Excercice 3
# calculate mean age of males df_males = df[df['Sex' == 'male']] df_males['Age'].mean() # Number of passenger aged > 70 (df['Age']>70).sum() # select the passenger between 30 and 40 years old aged30_40 = df[(df['Age'] >=30) & (df['Age'] <= 40)] # For a single string name = 'Braund, Mr. Owen Harris', split this string (check the split() method of a string) and get the first element of the resulting list name = 'Braund, Mr. Owen Harris' name.split(",")[0] # Convert the solution of the previous exercise to all strings of the Name column at once. Split the 'Name' column on the ,, extract the first part (the surname), and add this as new column 'Surname' df['Surname'] = df['Name'].str.split(",").str.get(0) # Select all passenger that have a surname starting with 'Williams' df[df['Surname'].str.startswith('Williams')] # Select all rows for the passengers with a surname of more than 15 characters df[df['Surname'].str.len() > 15]
Dates and times in pandas
import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') s = pd.Series(['2016-12-09 10:00:00', '2016-12-09 11:00:00', '2016-12-09 12:00:00']) # string > date ts = pd.to_datetime(s) # get years ts.dt.year ts.dt.weekday ts.dt.hour #single row : no need to call "dt" ts[0].dayofweek #pour eviter la confusion : pd.to_datetime("2021-12-01", dayfirst=True) pd.to_datetime("09/12/2016", format="%d/%m/%Y")
A detailed overview of how to specify the format string, see the table in the python documentation: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
# add an amount of time to each element of the series ts + pd.Timedelta('6 days') #create time series pd.date_range(start="2024-01-01", periods=10, freq="D") pd.date_range(start="2024-01-01", end=2024-06-01, freq="MS") # start of the month
Set time as index in a dataframe:
data["Time"] = pd.to_datetime(data['Time']) data = data.set_index("Time") data["L06_347"] # show time as index data.index data.index.dayofyear
Select data (a slice)
data[pd.to_datetime("2012-01-05"):pd.to_datetime("2012-01-10")] data["2012-01-05":"2012-05-10"] # the same data["2012-01":"2012-02"] # from start of Jan to the end of Feb data["2012-01":"2012-01"] # whole Jan month data["2012":"2012"] # whole year 2012 data["2012":] # until the end data[:"2012"] # from start until the end of 2012
Exercice 4
data = pd.read_csv("data/vmm_flowdata.csv", index_col=0, parse_dates=True) # select dates from start of 2012 to the end data["2012":] # Select all data in January for all different years data[data.index.month == 1] # Select all data in April, May and June for all different years data[(data.index.month == 4) | (data.index.month == 5) | (data.index.month == 6)] data[data.index.month.isin([4, 5, 6])] # Select all 'daytime' data (between 8h and 20h) for all days data[(data.index.hour>8) & (data.index.hour<20)]
Resample
Taking the mean of each month/year(end) (all data for a day are put together):
data.resample('D').mean() data.resample('YE').mean() data.resample('YE').max()
liste des intervalles : http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases
Exercice 4 (suite)
#... # Plot the monthly mean and median values for the years 2011-2012 for 'L06_347'. Use the last day of each month to represent the month. data[data.index.year.isin([2011, 2012])]['L06_347'].resample("ME").agg(["mean", "median"]).plot() subset = data['2011':'2012']['L06_347'] subset.resample('ME').agg(['mean', 'median']).plot() # Plot the monthly mininum and maximum daily average value of the 'LS06_348' column. Use the first day of each month to represent the month. daily_avg = data["LS06_348"].resample("D").mean() daily_avg.resample("ME").agg(["min", "max"]) # Make a bar plot of the mean of the stations in year of 2013 data["2013":"2013"].mean().plot.barh()
Data processing
Exercice 5 : bike 1
# read the file df = pd.read_csv("data/fietstelpaal-coupure-links-2022-gent.zip", sep=';') #Convert the 'Ordening' column into a pandas Timestamp Series, and assign the data to a new column named "timestamp". Make sure to read the data as UTC df["timestamp"] = pd.to_datetime (df["Ordening"], format="%Y-%m-%dT%H:%M:%S%z", utc=True) # Set the resulting "timestamp" column as the index of the df DataFrame df = df.set_index("timestamp") # drop columns df2022 = df.drop(columns=['Datum', 'Uur5Minuten', 'Ordening', 'Code']) # rename columns df2022 = df2022.rename(columns={"Tegenrichting":"direction_centre", "Hoofdrichting":"direction_mariakerke", "Locatie": "location", "Totaal": "total"}) # method chaining (df2022 = df .set_index("timestamp") .drop(columns=['Datum', 'Uur5Minuten', 'Ordening', 'Code']) .rename(columns={"Tegenrichting":"direction_centre", "Hoofdrichting":"direction_mariakerke", "Locatie": "location", "Totaal": "total"})
Group by
import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn-v0_8-whitegrid') df = pd.DataFrame({'key':['A','B','C','A','B','C','A','B','C'], 'data': [0, 5, 10, 5, 10, 15, 10, 15, 20]}) df # calculate mean by key df["data"][df["key"] == "A"].mean() df["data"][df["key"] == "B"].mean() df["data"][df["key"] == "C"].mean() # faster: df.groupby("key")["data"].mean() df.groupby("key")["data"].agg("mean")
Exercice 6
import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn-v0_8-whitegrid') df = pd.read_csv("data/titanic.csv") # Using groupby(), calculate the average age for each sex df.groupby("Sex")["Age"].mean() # Calculate the average survival ratio for all passengers df['Survived'].mean() # Calculate this survival ratio for all passengers younger than 25 df[(df['Age'] < 25)]["Survived"].mean() # What is the difference in the survival ratio between the sexes? df.groupby("Sex")["Survived"].mean() # Make a bar plot of the survival ratio for the different classes ('Pclass' column) df.groupby("Pclass")["Survived"].mean().plot.bar() # Make a bar plot to visualize the average Fare payed by people depending on their age. The age column is divided in separate classes using the pd.cut() function as provided below df['AgeClass'] = pd.cut(df['Age'], bins=np.arange(0,90,10)) df.groupby('AgeClass', observed=False)['Fare'].mean().plot.bar(rot=0)
groupby sur plusieurs variables :
df.groupby(["Pclass", "Sex"])["Survived"].mean()
