Lecture 19 live coding: Data wrangling with ecological data#
2026-11-24
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
Part 1: Understanding the raw data#
We have messy table, landplots_raw, which corresponds to land-plot-level data:
plot_id: unique identifier for each plotecosystem_type: type of ecosystem (e.g., grassland, shrubland, forest)trt_fertilizer_group: treatment groupbiomass_2023: above-ground biomass in 2023 (g/m^2)biomass_2024: above-ground biomass in 2024 (g/m^2)soil_nitrogen_pct: soil nitrogen content prior to fertilization
Lets first inspect the structure of the dataframe:
landplots_raw = pd.read_csv("~/COMSC-341CD/data/plots_raw.csv")
# inspect the rows, columns, and data types
# COMPLETED CELL
# # inspect the rows, columns, and data types
# print("landplots_raw shape:", landplots_raw.shape)
# landplots_raw.info()
# landplots_raw.head()
Units and IDs#
For causal analysis, we need to be clear about what counts as a unit and how it is identified. We’ll use plot_id to check for uniqueness and duplicates. Let’s answer the following questions:
How many duplicated rows are there in
landplots_raw?Which
plot_ids, if any, are duplicated?
# print the number of duplicated rows
# print the duplicated plot_ids
# COMPLETED CELL
# # print the number of duplicated rows
# print(landplots_raw.shape[0] - landplots_raw['plot_id'].nunique())
# # print the duplicated plot_ids
# print(landplots_raw[landplots_raw.duplicated(subset=['plot_id'])]['plot_id'])
# # look at one of the duplicated plots
# landplots_raw[landplots_raw['plot_id'] == 501]
Then, we can drop the duplicates. Instead of overwriting landplots_raw, we’ll create a new variable landplots_clean to preserve the original data.
landplots_clean = landplots_raw.copy()
# drop duplicates from landplots_clean
# COMPLETED CELL
# landplots_clean = landplots_raw.copy()
# # drop duplicates from landplots_clean
# landplots_clean = landplots_clean.drop_duplicates(subset=['plot_id'])
# # should now be 0
# print(landplots_clean.shape[0] - landplots_clean['plot_id'].nunique())
Part 2: Cleaning variables and columns#
Next, we will clean key variables in landplots_clean:
standardize
ecosystem_typelabelsrename
trt_fertilizer_grouptotreatment_groupstandardize
treatment_grouplabels in a new columntreatment_group_cleancreate a binary indicator in a new column
treated
# standardize ecosystem_type labels
# rename trt_fertilizer_group to treatment_group
# standardize treatment_group labels in a new column treatment_group_clean
# treated binary treatment indicator: 1 if nitrogen fertilized, 0 if control
# COMPLETED CELL
# # standardize ecosystem_type labels
# landplots_clean['ecosystem_type'] = landplots_clean['ecosystem_type'].str.strip().str.lower()
# print(landplots_clean['ecosystem_type'].unique())
# # rename trt_fertilizer_group to treatment_group
# landplots_clean = landplots_clean.rename(columns={'trt_fertilizer_group': 'treatment_group'})
# # standardize treatment_group labels in a new column treatment_group_clean
# print(landplots_clean['treatment_group'].unique())
# landplots_clean['treatment_group_clean'] = landplots_clean['treatment_group'].replace({'T': 'fert', 'C': 'control'})
# print(landplots_clean['treatment_group_clean'].unique())
# # treated binary treatment indicator: 1 if nitrogen fertilized, 0 if control
# landplots_clean['treated'] = np.where(landplots_clean['treatment_group_clean'] == 'fert', 1, 0)
# landplots_clean.head()
Part 3: Missingness and bad values#
The biomass variables contain special codes and implausible values.
We’ll first recode -99 as NaN in biomass_2023 and biomass_2024:
# replace -99 with NaN in `biomass_2023` and `biomass_2024`
# COMPLETED CELL
# # replace -99 with NaN in `biomass_2023` and `biomass_2024`
# landplots_clean['biomass_2023'] = landplots_clean['biomass_2023'].replace(-99, np.nan)
# landplots_clean['biomass_2024'] = landplots_clean['biomass_2024'].replace(-99, np.nan)
Additionally, there are some implausible (negative) values in biomass_2023. We’ll flag these with an indicator
biomass_2023_implausible, and also set those values in biomass_2023 to NaN:
# flag implausible biomass values with an indicator
# set implausible biomass values in `biomass_2023` column to NaN
# COMPLETED CELL
# # flag implausible biomass values with an indicator
# landplots_clean['biomass_2023_implausible'] = landplots_clean['biomass_2023'] < 0
# print(landplots_clean['biomass_2023_implausible'].sum())
# # set implausible biomass values in `biomass_2023` column to NaN
# landplots_clean.loc[landplots_clean['biomass_2023_implausible'], 'biomass_2023'] = np.nan
Next, we’ll check the missingness rates of the variables. What percentage of values are missing in biomass_2023 and biomass_2024?
# check the missingness rates of the variables
# COMPLETED CELL
# # check the missingness rates of the variables
# print(landplots_clean['biomass_2023'].isna().mean())
# print(landplots_clean['biomass_2024'].isna().mean())
Part 4: Wide vs long data formats#
Currently, our landplots_clean dataframe is violating the tidy data principle of “one row = one observation”, due to the two biomass columns.
We can use pd.melt() to convert the dataframe from wide to long format. This pandas function “unpivots” (or “melts”) the dataframe, turning multiple columns into a single column of values, and the column names into a new column with our choice of name. Specifically, it takes the following arguments:
id_vars: columns to keep as identifier variablesvalue_vars: columns to unpivotvar_name: name of the newvariablecolumnvalue_name: name of the newvaluecolumn
# melt the dataframe from wide to long format
landplots_long = None
# clean the year column to be numeric (e.g., 2023, 2024)
# COMPLETED CELL
# # melt the dataframe from wide to long format
# landplots_long = pd.melt(
# landplots_clean,
# id_vars=["plot_id", "ecosystem_type", "treated"],
# value_vars=["biomass_2023", "biomass_2024"],
# var_name="year",
# value_name="biomass",
# )
# # clean the year column to be numeric (e.g., 2023, 2024)
# landplots_long["year"] = landplots_long["year"].apply(lambda x: x.split("_")[1]).astype(int)
# # each plot now has two rows, one per year
# print(landplots_long.shape)
# landplots_long.sort_values(by="plot_id").head()
Now that our data is in long format, we can visualize the average biomass over the two timepoints by treatment group using a sns.lineplot() with:
x = yeary = biomasshue = treated
# plot a line plot of biomass over time by treatment group
# COMPLETED CELL
# # plot a line plot of biomass over time by treatment group
# sns.lineplot(data=landplots_long, x="year", y="biomass", hue="treated")
# plt.xticks([2023, 2024])
# plt.xlabel("Year")
# plt.ylabel("Above-ground biomass (g/m^2)")
# plt.title("Average biomass by treatment group")
Finally, if we’d like to return to the wide format, we can use pd.pivot() to pivot the dataframe from long to wide format. This function takes the following arguments:
index: column(s) to use as the index (rows)columns: variable to use as the columns: one new column for each unique valuevalues: column to use as the values to fill the new dataframe cells
# pivot the dataframe from long to wide format
# index = plot_id
# columns = year
# values = biomass
landplots_wide = None
# COMPLETED CELL
# # pivot the dataframe from long to wide format
# # index = plot_id
# # columns = year
# # values = biomass
# landplots_wide = landplots_long.pivot(
# index="plot_id",
# columns="year",
# values="biomass",
# )
# landplots_wide.head()