User Tools

Site Tools


python:datawrangling

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
python:datawrangling [2024/12/01 19:12] – [Day 1] carlpython:datawrangling [2024/12/03 08:27] (current) – Day 2 carl
Line 336: Line 336:
 groupby sur plusieurs variables : groupby sur plusieurs variables :
 <code python>df.groupby(["Pclass", "Sex"])["Survived"].mean()</code> <code python>df.groupby(["Pclass", "Sex"])["Survived"].mean()</code>
 +
 +====== Day 2 ======
 +===== Seaborn ======
 +  * built on matlibplot
 +  * works wel with panda
 +
 +<code python>import seaborn sas sns</code>
 +Puis, sns. et tab -> les possibilités
 +
 +<code python>titanic[['Age', 'Fare']].plot()</code>
 +OK pour un premier coup d'oeil
 +
 +<code python>
 +#For each class at the Titanic aneach gender, what was the average age
 +titanic.groupby(['Pclass', 'Sex'])[['Age'].mean()
 +type(titanic.groupby(['Pclass', 'Sex'])[['Age'].mean()) # type = multiindex
 +#add a new index
 +age_stat = titanic.groupby(['Pclass', 'Sex'])[['Age'].mean().reset_index() #.reset_index() = output dataframe instead of series
 +
 +#how to vizualize it?
 +titanic.groupby(['Pclass', 'Sex'])[['Age'].mean().plot() #too limited
 +
 +sns.catplot(data=age_stat, x="Sex", y="Age", col="Pclass", kind="bar")
 +#with colours for classes
 +sns.catplot(data=age_stat, x="Sex", y="Age", hue="Pclass", kind="bar")
 +#another way of seeing it
 +sns.catplot(data=age_stat, hue="Sex", y="Age", x="Pclass", kind="bar")
 +</code>
 +
 +type of plots (3 functions : relplot, catplot & displot and several kinds kind="pointplot"):
 +  * relation plot (relplot) : scatterplot, lineplot
 +  * distribution plot (distplot) : histpolot, kdeplot, ecdfplot, rugplot
 +  * categorical plot (catplot) : stripplot, swarmplot, boxplot, violinplot, pointplot, barplot
 +
 +<code python>sns.relplot
 +sns.catplot
 +sns.displot(data=titanic, x='Age', kind="hist")
 +# col = 2 separate plots (hue = colour for survival)
 +age_fare = sns.relplot(data=titanic, x="Age", y="Fare",
 +                       hue="Survived",
 +                       col="Sex")
 +                       
 +#see that more females survived: better this:
 +age_fare = sns.relplot(data=titanic, x="Age", y="Fare",
 +                       col="Survived",
 +                       hue="Sex")
 +</code>
 +
 +relplot : col= , row= pour splitter le graphique en plusieurs, mais pas possible avec les 2 autres fonctions
 +
 +Exercices
 +<code python>#Make a histogram of the age, split up in two subplots by the Sex of the passengers.
 +#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, x="Age", kind="hist", row="Sex", height=4, aspect=2)
 +#more bins:
 +sns.displot(data=titanic, x="Age", kind="hist", row="Sex", height=4, aspect=2, bins=60)
 +
 +# Make a violin plot showing the Age distribution in each of the Pclass categories comparing for Sex
 +# Figure based
 +sns.catplot(data=titanic, x="Pclass", y="Age", 
 +            hue="Sex", split=True,
 +            palette="Set2", kind="violin")
 +sns.despine(left=True)
 +# Axes based
 +sns.violinplot(data=titanic, x="Pclass", y="Age", 
 +               hue="Sex", split=True,
 +               palette="Set2")
 +sns.despine(left=True)</code>
 +
 +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()</code>
 +
 +==== Exercices ====
 +<code python>casualties["gender"].unique()</code
 +all values in gender variable
 +
 +Create a barplot with the number of victims ("n_victims") for each hour of the day for each category in the gender column. Before plotting, calculate the total number of victims for each hour of the day and each gender with Pandas and assign it to the variable victims_gender_hour_of_day.
 +
 +Create a separate subplot for each gender category in a separate row.
 +
 +Make sure to include the NaN values of the "gender" column as a separate subplot, called "unknown" without changing the casualties DataFrame data.
 +<code python>victims_gender_hour_of_day = casualties.groupby([casualties["datetime"].dt.hour, "gender"], 
 +                                                dropna=False)["n_victims"].sum().reset_index()
 +victims_gender_hour_of_day.head()
 +
 +victims_gender_hour_of_day = casualties.groupby([casualties["datetime"].dt.hour, "gender"], dropna=False)["n_victims"].sum().reset_index()
 +victims_gender_hour_of_day.head()
 +sns.catplot(data=victims_gender_hour_of_day.fillna("unknown"), x='datetime', y='n_victims', row='gender', kind='bar', height=3, aspect=3)</code>
 +
 +===== Tidy data =====
 +In a tidy dataset :
 +  * each variable is a row
 +  * each observation is a line
 +
 +<code python>import pandas as pd
 +import numpy as np
 +import matplotlib.pyplot as plt
 +import seaborn as sns
 +
 +# create dataset
 +data = pd.DataFrame({
 +   'WWTP': ['Destelbergen', 'Landegem', 'Dendermonde', 'Eeklo'],
 +   'Treatment A': [8.0, 7.5, 8.3, 6.5],
 +   'Treatment B': [6.3, 5.2, 6.2, 7.2]
 +})
 +data
 +
 +# go from a wide to a long data format
 +pd.melt(data, id_vars=["WWTP"])
 +
 +data_long = pd.melt(data, id_vars=["WWTP"], 
 +                    value_name="pH", var_name="Treatment")
 +data_long
 +
 +data_long.groupby("Treatment")["pH"].mean()
 +data_long.groupby("WWTP")["pH"].mean()
 +
 +sns.catplot(data=data_long, x="WWTP", y="pH", 
 +            hue="Treatment", kind="bar")
 +sns.catplot(data=data_long, x="Treatment", y="pH", 
 +            hue="WWTP", kind="bar")
 +</code>
 +
 +==== Exercices ====
 +
 +<code python>
 +#Read the "verbruiksgegevens-per-maand.xlsx" file (in the "data/" directory) into a DataFrame df.
 +df = pd.read_excel("data/verbruiksgegevens-per-maand.xlsx")
 +#Drop the "Regio" column (this column has a constant value "Regio 1" and thus is not that interesting).
 +df = df.drop(columns=["Regio"])
 +df
 +</code>
 +
 +The actual data (consumption numbers) is spread over multiple columns: one column per month. Make a tidy version of this dataset with a single "consumption" column, and an additional "time" column.
 +
 +Make sure to keep the "Hoofdgemeente", "Energie" and "SLP" columns in the data set. The "SLP" column contains additional categories about the type of elektricity or gas consumption (eg household vs non-household consumption).
 +
 +Use pd.melt() to create a long or tidy version of the dataset, and call the result df_tidy.
 +<code python>df_tidy = pd.melt(df, id_vars=["Hoofdgemeente", "Energie", "SLP"], var_name="time", value_name="consumption")
 +df_tidy
 +#Convert the "time" column to a column with a datetime data type using pd.to_datetime.
 +df_tidy["time"] = pd.to_datetime(df_tidy["time"], format="%Y%m")
 +df_tidy.head()
 +</code>
 +
 +Calculate the total consumption of elektricity and gas over all municipalities ("Hoofdgemeente") for each month. 
 +
 +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 = df_tidy.groupby(["time", "Energie"])[["consumption"]].sum() # or with .reset_index()
 +df_overall.head()
 +
 +facet = sns.relplot(x="time", y="consumption", col="Energie",
 +                    data=df_overall, kind="line")
 +facet.set(ylim=(0, None)) # (min, max)</code>
 +
 +===== Pivot table =====
 +  * .pivot : no recalculations, only rearrange
 +  * .pivot_table : recalculations = common way to summarize the data
 +<code python>df = pd.read_csv("data/titanic.csv")
 +df.pivot_table(index='Sex', columns='Pclass', values='Fare')
 +
 +df_full.pivot_table(columns="Pclass", index="Sex", values="Fares")
 +df_full.pivot_table(columns="Pclass", index="Sex", values="Fares", aggfunc="mean") # mean = default
 +df_full.pivot_table(columns="Pclass", index="Sex", values="Fares", aggfunc="min") # or max, std, count, etc.
 +# function crosstab = pivot_table with aggfunc="count"
 +</code>
 +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("data/titanic.csv")
 +df.pivot_table(index='Pclass', columns='Sex', 
 +               values='Survived', aggfunc='mean')
 +# extra : graph
 +fig, ax1 = plt.subplots()
 +(df.pivot_table(index='Pclass', columns='Sex', 
 +               values='Survived', aggfunc='mean')
 +   .plot.bar(rot=0, ax=ax1)
 +)
 +ax1.set_ylabel('Survival ratio')
 +
 +#Make a table of the median Fare payed by aged/underaged vs Sex.
 +df['Underaged'] = df['Age'] <= 18 # boolean variable
 +(df.pivot_table(
 +    index='Underaged', columns='Sex', values='Fare', aggfunc='median')
 +    .rename(columns={'False' : 'underaged', 'True':'aged'}
 +)
 +          </code>
 +A pivot table aggregates values for each combination of the new row index and column values. That reminds of the "groupby" operation.
 +
 +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.groupby(["Pclass", "Sex"])["Survived"].mean().reset_index()
 +df_survival
 +df_survival.pivot(index="Pclass", columns="Sex", values="Survived")</code>
 +
 +==== Case study 3 : bacterial resistance ====
 +<code>import pandas as pd
 +import seaborn as sns
 +import matplotlib.pyplot as plt
 +
 +Seaborn custom color palettes : doc "choosing color palettes"
 +https://colorbrewer2.org/
 +3 categories :
 +  * sequential : variable continue qui augmente
 +  * diverging : e.g. temperatures (valeurs centrales, puis d'autres valeures des 2 côtés, + et -)
 +  * qualitative : catégories
 +
 +<code python>sns.catplot(..., palette="colorblind")
 +# select an pre-built set globally, not always working, better as parameter
 +sns.colorpalette("icefire", as_cmap=True")</code>
 +
 +===== Matplotlib: visualisation with Python =====
 +  * very adaptable (e.g. plot within a plot)
 +  * difficult to master
 +  * output for a paper/report
 +  * add a line at some specific threshold to a figure generated with Seaborn
 +
 +<code python>import numpy as np
 +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("title 1")
 +
 +fig, ax = plt.subplots(nrows=1, ncols=2)
 +print(ax) # actually axes
 +
 +ax[0].set_title=("LEFT")
 +ax[1].set_title=("RIGHT")
 +
 +fig, (ax0, ax1) = plt.subplots(nrows=1, ncols=2)
 +
 +ax0.set_title=("LEFT")
 +ax1.set_title=("RIGHT")
 +
 +fig.savefig() #save the figure in file
 +
 +plt.plot(x, y, "-")
 +plt.title("title 2")
 +#not object-oriented programme, try to avoid -> assign it to an object
 +fig, ax = plt.subplots()
 +ax.plot(x, y, "-")
 +ax.set_title("title2")
 +# gives the same result
 +
 +# avoid 1e7 on the y-axis
 +ax.yaxis.set_major_formatter(ticker;FormatStrFormatter("%.1f"))
 +</code>
 +
 +Reference graph with objects that can be customised :
 +  * major tick
 +  * minor tick
 +  * line
 +  * grid
 +  * title
 +  * legend
 +  * spine
 +  * x-label
 +  * etc.
 +
 +different styles
 +<code python>plt.style.available
 +
 +#define at the script level
 +plt.style.use("tableau-colorblind10")
 +
 +#set up several plots
 +axd = plt.figure(constrained_layout=True).subplot_mosaic(
 +    """
 +    ABD
 +    CCD
 +    """
 +)
 +axd
 +axd["A"].set_title("A it is")
 +</code>
 +
 +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 title")
 +my_output.set_ylabel('r'Discharge m3/s')</code>
 +
 +Dans pandas, on peut passer un axe créé avec matplotlib comme paramètre:
 +<code python>
 +fig, (ax0, ax1) = plt.subplots(1, 2)
 +flowdata.plot()</code>
 +
 +<code python>histplot = sns.displot(data=tidy_experiment, x="optical_density", color="grey", edgecolor="white"))
 +histplot.axes.shape[0][0] # axes = array 2 x 2
 +histplot.axes[0, 0].avxline(0.4, color="blue") # vertical blue line at x=0.4
 +histplot.axes[0, 0].ahxline(600, color="red") # horizontal: avx? ahy?
 +# cf. arrays:
 +my_array = np.array([[1, 2], [3, 4]])
 +my_array[1, 1]
 +
 +#seaborn returns an array, even if only one figure :
 +my_array = np.array([[1]])
 +my_arry[0, 0] 
 +</code>
 +
 +===== Data cleaning in Pandas =====
 +  * drop, rename columns
 +  * replace, explode values
 +
 +https://excalidraw.com/ : draw figures online
 +
 +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 numpy as np
 +import pandas as pd
 +
 +df = pd.DataFrame({'A': [1, 2, np.nan],
 +                   'B': [4, np.nan, np.nan],
 +                   'C': [7, 8, 9]})
 +df
 +df.types # columns without NaN = int, those with NaN = float</code>
 +
 +By default, .mean() skips NaN (missing values)
 +Can be avoided:
 +<code python>df["A"].mean(skipna=False) # if there are NaN, the mean with also be NaN
 +
 +df["A"] + 10 # add 10 to each number from the column - N.B.: NaN+10 = NaN
 +
 +df["A"] > 1 # comparing with NaN always returns False : when selecting, NaN values will be excluded (always False)
 +df["A"].isna()
 +df[df["A"].isna()] # select missing values
 +df[df["A"].notna()] # select non missing values
 +
 +# count missing values in a column
 +df["A"].isna().sum()
 +
 +df.dropna() # drop rows where at least one NaN
 +df.dropna(subset="A") # drop rows where NaN in column "A"
 +df.dropna(subset=["A", "B"], how="all")
 +
 +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='linear') # to fill in the NaN values
 +
 +df.ffill() #forward fill: looks at last non missing value and find the next value to attribute
 +df.bfill() #backward fill
 +df["B"].interpolate(method="nearest") # nearest value
 +</code>
 +
 +===== Conclusion =====
 +  * some extra chapters not seen
 +    * Pandas : combining data (concatenate, join, merge several dataframes)
 +  * some extra cases to discover (case 4 : missing values ; case 2 : fishing = groupby, duplicate...)
python/datawrangling.1733080371.txt.gz · Last modified: by carl