python:datawrangling
Differences
This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
| python:datawrangling [2024/11/27 08:20] – created carl | python:datawrangling [2024/12/03 08:27] (current) – Day 2 carl | ||
|---|---|---|---|
| Line 5: | Line 5: | ||
| https:// | https:// | ||
| + | |||
| + | ===== Day 0 : préparation ====== | ||
| + | |||
| + | Après avoir installé [[https:// | ||
| + | < | ||
| + | |||
| + | il faut activer l' | ||
| + | < | ||
| + | |||
| + | Télécharger le fichier pour préciser l' | ||
| + | < | ||
| + | |||
| + | qui contient : | ||
| + | < | ||
| + | channels: | ||
| + | - conda-forge | ||
| + | dependencies: | ||
| + | - python=3.11 | ||
| + | - ipython | ||
| + | - jupyter | ||
| + | - jupyterlab> | ||
| + | - numpy | ||
| + | - pandas> | ||
| + | - matplotlib> | ||
| + | - mplleaflet | ||
| + | - ipympl | ||
| + | - seaborn | ||
| + | - plotnine | ||
| + | - pyproj | ||
| + | - requests | ||
| + | - openpyxl</ | ||
| + | |||
| + | Ensuite, dans Anaconda : base (root) > Terminal : | ||
| + | < | ||
| + | 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 : | ||
| + | < | ||
| + | ipython</ | ||
| + | pour ouvrir un terminal python où taper : | ||
| + | <code python> | ||
| + | import matplotlib</ | ||
| ===== Day 1 ====== | ===== Day 1 ====== | ||
| + | |||
| + | < | ||
| + | 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' | ||
| + | |||
| + | * pour créer une nouvelle fenêtre dans laquelle écrire du code : cliquer sur une fenêtre existente, appuyer sur la touche " | ||
| + | * pour faire tourner du code, cliquer sur la fenêtre (pour y avoir le curseur), ensuite shift + touche " | ||
| + | |||
| + | Pour avoir de l'aide sur un objet <code python> | ||
| + | Pour avoir de l'aide sur les paramètres d'une fonction, faire shift + " | ||
| ===== Pandas ===== | ===== Pandas ===== | ||
| dataframe : object with rows and columns | dataframe : object with rows and columns | ||
| Line 41: | Line 101: | ||
| ==== Exercice 1 ==== | ==== Exercice 1 ==== | ||
| - | <code python> | + | <code python>import pandas as pd |
| # importer les données dans un dataframe | # importer les données dans un dataframe | ||
| df=pd.read_csv(" | df=pd.read_csv(" | ||
| Line 276: | Line 336: | ||
| groupby sur plusieurs variables : | groupby sur plusieurs variables : | ||
| <code python> | <code python> | ||
| + | |||
| + | ====== Day 2 ====== | ||
| + | ===== Seaborn ====== | ||
| + | * built on matlibplot | ||
| + | * works wel with panda | ||
| + | |||
| + | <code python> | ||
| + | Puis, sns. et tab -> les possibilités | ||
| + | |||
| + | <code python> | ||
| + | OK pour un premier coup d'oeil | ||
| + | |||
| + | <code python> | ||
| + | #For each class at the Titanic aneach gender, what was the average age | ||
| + | titanic.groupby([' | ||
| + | type(titanic.groupby([' | ||
| + | #add a new index | ||
| + | age_stat = titanic.groupby([' | ||
| + | |||
| + | #how to vizualize it? | ||
| + | titanic.groupby([' | ||
| + | |||
| + | sns.catplot(data=age_stat, | ||
| + | #with colours for classes | ||
| + | sns.catplot(data=age_stat, | ||
| + | #another way of seeing it | ||
| + | sns.catplot(data=age_stat, | ||
| + | </ | ||
| + | |||
| + | type of plots (3 functions : relplot, catplot & displot and several kinds kind=" | ||
| + | * relation plot (relplot) : scatterplot, | ||
| + | * distribution plot (distplot) : histpolot, kdeplot, ecdfplot, rugplot | ||
| + | * categorical plot (catplot) : stripplot, swarmplot, boxplot, violinplot, pointplot, barplot | ||
| + | |||
| + | <code python> | ||
| + | sns.catplot | ||
| + | sns.displot(data=titanic, | ||
| + | # col = 2 separate plots (hue = colour for survival) | ||
| + | age_fare = sns.relplot(data=titanic, | ||
| + | | ||
| + | | ||
| + | |||
| + | #see that more females survived: better this: | ||
| + | age_fare = sns.relplot(data=titanic, | ||
| + | | ||
| + | | ||
| + | </ | ||
| + | |||
| + | relplot : col= , row= pour splitter le graphique en plusieurs, mais pas possible avec les 2 autres fonctions | ||
| + | |||
| + | Exercices | ||
| + | <code python># | ||
| + | #Put both subplots underneath each other. | ||
| + | #Use the height and aspect arguments of the plot function to adjust the size of the figure. | ||
| + | sns.displot(data=titanic, | ||
| + | #more bins: | ||
| + | sns.displot(data=titanic, | ||
| + | |||
| + | # Make a violin plot showing the Age distribution in each of the Pclass categories comparing for Sex | ||
| + | # Figure based | ||
| + | sns.catplot(data=titanic, | ||
| + | hue=" | ||
| + | palette=" | ||
| + | sns.despine(left=True) | ||
| + | # Axes based | ||
| + | sns.violinplot(data=titanic, | ||
| + | | ||
| + | | ||
| + | sns.despine(left=True)</ | ||
| + | |||
| + | Aussi jointplot et pairplot qui montre la distribution le long des axes (jointplot) ou des carrés de graphiques (pairplot) | ||
| + | <code python> | ||
| + | #linear regression plot | ||
| + | sns.lmplot() | ||
| + | sns.regplot()</ | ||
| + | |||
| + | ==== Exercices ==== | ||
| + | <code python> | ||
| + | all values in gender variable | ||
| + | |||
| + | Create a barplot with the number of victims (" | ||
| + | |||
| + | Create a separate subplot for each gender category in a separate row. | ||
| + | |||
| + | Make sure to include the NaN values of the " | ||
| + | <code python> | ||
| + | dropna=False)[" | ||
| + | victims_gender_hour_of_day.head() | ||
| + | |||
| + | victims_gender_hour_of_day = casualties.groupby([casualties[" | ||
| + | victims_gender_hour_of_day.head() | ||
| + | sns.catplot(data=victims_gender_hour_of_day.fillna(" | ||
| + | |||
| + | ===== Tidy data ===== | ||
| + | In a tidy dataset : | ||
| + | * each variable is a row | ||
| + | * each observation is a line | ||
| + | |||
| + | <code python> | ||
| + | import numpy as np | ||
| + | import matplotlib.pyplot as plt | ||
| + | import seaborn as sns | ||
| + | |||
| + | # create dataset | ||
| + | data = pd.DataFrame({ | ||
| + | ' | ||
| + | ' | ||
| + | ' | ||
| + | }) | ||
| + | data | ||
| + | |||
| + | # go from a wide to a long data format | ||
| + | pd.melt(data, | ||
| + | |||
| + | data_long = pd.melt(data, | ||
| + | value_name=" | ||
| + | data_long | ||
| + | |||
| + | data_long.groupby(" | ||
| + | data_long.groupby(" | ||
| + | |||
| + | sns.catplot(data=data_long, | ||
| + | hue=" | ||
| + | sns.catplot(data=data_long, | ||
| + | hue=" | ||
| + | </ | ||
| + | |||
| + | ==== Exercices ==== | ||
| + | |||
| + | <code python> | ||
| + | #Read the " | ||
| + | df = pd.read_excel(" | ||
| + | #Drop the " | ||
| + | df = df.drop(columns=[" | ||
| + | df | ||
| + | </ | ||
| + | |||
| + | The actual data (consumption numbers) is spread over multiple columns: one column per month. Make a tidy version of this dataset with a single " | ||
| + | |||
| + | Make sure to keep the " | ||
| + | |||
| + | Use pd.melt() to create a long or tidy version of the dataset, and call the result df_tidy. | ||
| + | <code python> | ||
| + | df_tidy | ||
| + | #Convert the " | ||
| + | df_tidy[" | ||
| + | df_tidy.head() | ||
| + | </ | ||
| + | |||
| + | Calculate the total consumption of elektricity and gas over all municipalities (" | ||
| + | |||
| + | Assign the result to a dataframe called df_overall. | ||
| + | |||
| + | Using df_overall, make a line plot of the consumption of elektricity vs gas over time. | ||
| + | |||
| + | Create a separate subplot for elektricity and for gas, putting them next to each other. | ||
| + | |||
| + | Ensure that the y-limit starts at 0 for both subplots. | ||
| + | |||
| + | <code python> | ||
| + | df_overall.head() | ||
| + | |||
| + | facet = sns.relplot(x=" | ||
| + | data=df_overall, | ||
| + | facet.set(ylim=(0, | ||
| + | |||
| + | ===== Pivot table ===== | ||
| + | * .pivot : no recalculations, | ||
| + | * .pivot_table : recalculations = common way to summarize the data | ||
| + | <code python> | ||
| + | df.pivot_table(index=' | ||
| + | |||
| + | df_full.pivot_table(columns=" | ||
| + | df_full.pivot_table(columns=" | ||
| + | df_full.pivot_table(columns=" | ||
| + | # function crosstab = pivot_table with aggfunc=" | ||
| + | </ | ||
| + | for columns and index, you can pass lists [] to have more than one variable | ||
| + | |||
| + | ==== Exercices ==== | ||
| + | <code python># Make a pivot table with the survival rates for Pclass vs Sex. | ||
| + | df = pd.read_csv(" | ||
| + | df.pivot_table(index=' | ||
| + | | ||
| + | # extra : graph | ||
| + | fig, ax1 = plt.subplots() | ||
| + | (df.pivot_table(index=' | ||
| + | | ||
| + | | ||
| + | ) | ||
| + | ax1.set_ylabel(' | ||
| + | |||
| + | #Make a table of the median Fare payed by aged/ | ||
| + | df[' | ||
| + | (df.pivot_table( | ||
| + | index=' | ||
| + | .rename(columns={' | ||
| + | ) | ||
| + | </ | ||
| + | A pivot table aggregates values for each combination of the new row index and column values. That reminds of the " | ||
| + | |||
| + | Can you mimick the pivot table of the first exercise (a pivot table with the survival rates for Pclass vs Sex) using groupby()? | ||
| + | <code python> | ||
| + | df_survival | ||
| + | df_survival.pivot(index=" | ||
| + | |||
| + | ==== Case study 3 : bacterial resistance ==== | ||
| + | < | ||
| + | import seaborn as sns | ||
| + | import matplotlib.pyplot as plt | ||
| + | |||
| + | Seaborn custom color palettes : doc " | ||
| + | https:// | ||
| + | 3 categories : | ||
| + | * sequential : variable continue qui augmente | ||
| + | * diverging : e.g. temperatures (valeurs centrales, puis d' | ||
| + | * qualitative : catégories | ||
| + | |||
| + | <code python> | ||
| + | # select an pre-built set globally, not always working, better as parameter | ||
| + | sns.colorpalette(" | ||
| + | |||
| + | ===== Matplotlib: visualisation with Python ===== | ||
| + | * very adaptable (e.g. plot within a plot) | ||
| + | * difficult to master | ||
| + | * output for a paper/ | ||
| + | * add a line at some specific threshold to a figure generated with Seaborn | ||
| + | |||
| + | <code python> | ||
| + | import panda as pd | ||
| + | import matlibplot.pyplot as plt | ||
| + | |||
| + | ax = plt.axes() #x- and y-axis drawn | ||
| + | plt.subplots() | ||
| + | #output = 2 objects: | ||
| + | fig, ax = plt.subplots() | ||
| + | |||
| + | #you can then work on these 2 objects | ||
| + | ax.set_title(" | ||
| + | |||
| + | fig, ax = plt.subplots(nrows=1, | ||
| + | print(ax) # actually axes | ||
| + | |||
| + | ax[0].set_title=(" | ||
| + | ax[1].set_title=(" | ||
| + | |||
| + | fig, (ax0, ax1) = plt.subplots(nrows=1, | ||
| + | |||
| + | ax0.set_title=(" | ||
| + | ax1.set_title=(" | ||
| + | |||
| + | fig.savefig() #save the figure in file | ||
| + | |||
| + | plt.plot(x, y, " | ||
| + | plt.title(" | ||
| + | #not object-oriented programme, try to avoid -> assign it to an object | ||
| + | fig, ax = plt.subplots() | ||
| + | ax.plot(x, y, " | ||
| + | ax.set_title(" | ||
| + | # gives the same result | ||
| + | |||
| + | # avoid 1e7 on the y-axis | ||
| + | ax.yaxis.set_major_formatter(ticker; | ||
| + | </ | ||
| + | |||
| + | Reference graph with objects that can be customised : | ||
| + | * major tick | ||
| + | * minor tick | ||
| + | * line | ||
| + | * grid | ||
| + | * title | ||
| + | * legend | ||
| + | * spine | ||
| + | * x-label | ||
| + | * etc. | ||
| + | |||
| + | different styles | ||
| + | <code python> | ||
| + | |||
| + | #define at the script level | ||
| + | plt.style.use(" | ||
| + | |||
| + | #set up several plots | ||
| + | axd = plt.figure(constrained_layout=True).subplot_mosaic( | ||
| + | """ | ||
| + | ABD | ||
| + | CCD | ||
| + | """ | ||
| + | ) | ||
| + | axd | ||
| + | axd[" | ||
| + | </ | ||
| + | |||
| + | Graphs generated with pandas are actually generated by matplotlib -> assign to an object that you can then customize with matplotlib: | ||
| + | <code python> | ||
| + | my_output = flowdata.plot.iline() | ||
| + | my_output.set_title(" | ||
| + | my_output.set_ylabel(' | ||
| + | |||
| + | Dans pandas, on peut passer un axe créé avec matplotlib comme paramètre: | ||
| + | <code python> | ||
| + | fig, (ax0, ax1) = plt.subplots(1, | ||
| + | flowdata.plot()</ | ||
| + | |||
| + | <code python> | ||
| + | histplot.axes.shape[0][0] # axes = array 2 x 2 | ||
| + | histplot.axes[0, | ||
| + | histplot.axes[0, | ||
| + | # cf. arrays: | ||
| + | my_array = np.array([[1, | ||
| + | my_array[1, 1] | ||
| + | |||
| + | #seaborn returns an array, even if only one figure : | ||
| + | my_array = np.array([[1]]) | ||
| + | my_arry[0, 0] | ||
| + | </ | ||
| + | |||
| + | ===== Data cleaning in Pandas ===== | ||
| + | * drop, rename columns | ||
| + | * replace, explode values | ||
| + | |||
| + | https:// | ||
| + | |||
| + | Not seen in the course, see by yourself. | ||
| + | |||
| + | ===== Missing values in Pandas ===== | ||
| + | * NaN (not a number) = missing value | ||
| + | * NaN is a float (not an integer) | ||
| + | * NaN = np.nan | ||
| + | |||
| + | <code python> | ||
| + | import pandas as pd | ||
| + | |||
| + | df = pd.DataFrame({' | ||
| + | ' | ||
| + | ' | ||
| + | df | ||
| + | df.types # columns without NaN = int, those with NaN = float</ | ||
| + | |||
| + | By default, .mean() skips NaN (missing values) | ||
| + | Can be avoided: | ||
| + | <code python> | ||
| + | |||
| + | df[" | ||
| + | |||
| + | df[" | ||
| + | df[" | ||
| + | df[df[" | ||
| + | df[df[" | ||
| + | |||
| + | # count missing values in a column | ||
| + | df[" | ||
| + | |||
| + | df.dropna() # drop rows where at least one NaN | ||
| + | df.dropna(subset=" | ||
| + | df.dropna(subset=[" | ||
| + | |||
| + | df.fillna(0) # replace NaN values by 0 | ||
| + | df.fillna(mdf.median()) # replace NaN values by the median of the non missing values of that column | ||
| + | |||
| + | pd.Series.interpolate(method=' | ||
| + | |||
| + | df.ffill() #forward fill: looks at last non missing value and find the next value to attribute | ||
| + | df.bfill() #backward fill | ||
| + | df[" | ||
| + | </ | ||
| + | |||
| + | ===== Conclusion ===== | ||
| + | * some extra chapters not seen | ||
| + | * Pandas : combining data (concatenate, | ||
| + | * some extra cases to discover (case 4 : missing values ; case 2 : fishing = groupby, duplicate...) | ||
python/datawrangling.1732695628.txt.gz · Last modified: by carl
