Lecture 19 live coding [complete]: 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 plot

  • ecosystem_type: type of ecosystem (e.g., grassland, shrubland, forest)

  • trt_fertilizer_group: treatment group

  • biomass_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
landplots_raw.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 255 entries, 0 to 254
Data columns (total 7 columns):
 #   Column                Non-Null Count  Dtype  
---  ------                --------------  -----  
 0   plot_id               255 non-null    int64  
 1   site_id               255 non-null    object 
 2   ecosystem_type        255 non-null    object 
 3   biomass_2023          255 non-null    float64
 4   biomass_2024          255 non-null    float64
 5   trt_fertilizer_group  255 non-null    object 
 6   soil_nitrogen_pct     255 non-null    float64
dtypes: float64(3), int64(1), object(3)
memory usage: 14.1+ KB
# 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:

  1. How many duplicated rows are there in landplots_raw?

  2. Which plot_ids, if any, are duplicated?

# print the number of duplicated rows
print(landplots_raw['plot_id'].nunique())

# print the duplicated plot_ids
print(landplots_raw[landplots_raw.duplicated(subset=['plot_id'])]['plot_id'])

landplots_raw[landplots_raw['plot_id'] == 501]
250
250    501
251    532
252    619
253    604
254    688
Name: plot_id, dtype: int64
plot_id site_id ecosystem_type biomass_2023 biomass_2024 trt_fertilizer_group soil_nitrogen_pct
1 501 S1 forest 346.1 349.1 fert 0.452
250 501 S1 forest 346.1 349.1 fert 0.452
# 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
landplots_clean = landplots_clean.drop_duplicates(subset=['plot_id'])

landplots_clean['plot_id'].nunique()
250
# 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:

  1. standardize ecosystem_type labels

  2. rename trt_fertilizer_group to treatment_group

  3. standardize treatment_group labels in a new column treatment_group_clean

  4. create a binary indicator in a new column treated

# standardize ecosystem_type labels
landplots_clean['ecosystem_type'] = landplots_clean['ecosystem_type'].str.strip().str.lower()
print(landplots_clean['ecosystem_type'])

# rename trt_fertilizer_group to treatment_group
landplots_clean = landplots_clean.rename(columns={
    'trt_fertilizer_group': 'treat_group'
})

landplots_clean.head()

# standardize treatment_group labels in a new column treatment_group_clean
landplots_clean['trea
# treated binary treatment indicator: 1 if nitrogen fertilized, 0 if control
  Cell In[9], line 13
    landplots_clean['trea
                    ^
SyntaxError: unterminated string literal (detected at line 13)
print(landplots_clean['treat_group'].unique())

landplots_clean['treat_group'] = landplots_clean['treat_group'].replace({
    'T': 'fert',
    'C': 'control'
})

print(landplots_clean['treat_group'].unique())
landplots_clean['treated'] = np.where(landplots_clean['treat_group'] == 'fert', 1, 0)

print(landplots_clean[['treated', 'treat_group']])
['fert' 'control']
['fert' 'control']
     treated treat_group
0          1        fert
1          1        fert
2          0     control
3          1        fert
4          1        fert
..       ...         ...
245        1        fert
246        0     control
247        1        fert
248        0     control
249        1        fert

[250 rows x 2 columns]
?np.where
Signature:       np.where(condition, x=None, y=None, /)
Call signature:  np.where(*args, **kwargs)
Type:            _ArrayFunctionDispatcher
String form:     <built-in function where>
Docstring:      
where(condition, [x, y], /)

Return elements chosen from `x` or `y` depending on `condition`.

.. note::
    When only `condition` is provided, this function is a shorthand for
    ``np.asarray(condition).nonzero()``. Using `nonzero` directly should be
    preferred, as it behaves correctly for subclasses. The rest of this
    documentation covers only the case where all three arguments are
    provided.

Parameters
----------
condition : array_like, bool
    Where True, yield `x`, otherwise yield `y`.
x, y : array_like
    Values from which to choose. `x`, `y` and `condition` need to be
    broadcastable to some shape.

Returns
-------
out : ndarray
    An array with elements from `x` where `condition` is True, and elements
    from `y` elsewhere.

See Also
--------
choose
nonzero : The function that is called when x and y are omitted

Notes
-----
If all the arrays are 1-D, `where` is equivalent to::

    [xv if c else yv
     for c, xv, yv in zip(condition, x, y)]

Examples
--------
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.where(a < 5, a, 10*a)
array([ 0,  1,  2,  3,  4, 50, 60, 70, 80, 90])

This can be used on multidimensional arrays too:

>>> np.where([[True, False], [True, True]],
...          [[1, 2], [3, 4]],
...          [[9, 8], [7, 6]])
array([[1, 8],
       [3, 4]])

The shapes of x, y, and the condition are broadcast together:

>>> x, y = np.ogrid[:3, :4]
>>> np.where(x < y, x, 10 + y)  # both x and 10+y are broadcast
array([[10,  0,  0,  0],
       [10, 11,  1,  1],
       [10, 11, 12,  2]])

>>> a = np.array([[0, 1, 2],
...               [0, 2, 4],
...               [0, 3, 6]])
>>> np.where(a < 4, a, -1)  # -1 is broadcast
array([[ 0,  1,  2],
       [ 0,  2, -1],
       [ 0,  3, -1]])
Class docstring:
Class to wrap functions with checks for __array_function__ overrides.

All arguments are required, and can only be passed by position.

Parameters
----------
dispatcher : function or None
    The dispatcher function that returns a single sequence-like object
    of all arguments relevant.  It must have the same signature (except
    the default values) as the actual implementation.
    If ``None``, this is a ``like=`` dispatcher and the
    ``_ArrayFunctionDispatcher`` must be called with ``like`` as the
    first (additional and positional) argument.
implementation : function
    Function that implements the operation on NumPy arrays without
    overrides.  Arguments passed calling the ``_ArrayFunctionDispatcher``
    will be forwarded to this (and the ``dispatcher``) as if using
    ``*args, **kwargs``.

Attributes
----------
_implementation : function
    The original implementation passed in.
# 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`
landplots_clean['biomass_2023'] = landplots_clean['biomass_2023'].replace(-99, np.nan)
landplots_clean['biomass_2024'] = landplots_clean['biomass_2024'].replace(-99, np.nan)
# 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 variables

  • value_vars: columns to unpivot

  • var_name: name of the new variable column

  • value_name: name of the new value column

landplots_clean.head()
plot_id site_id ecosystem_type biomass_2023 biomass_2024 treat_group soil_nitrogen_pct treated
0 500 S4 forest 245.5 185.5 fert 0.300 1
1 501 S1 forest 346.1 349.1 fert 0.452 1
2 502 S1 grassland 604.1 659.3 control 0.486 0
3 503 S1 forest 452.0 431.5 fert 0.417 1
4 504 S2 forest 329.5 402.2 fert 0.515 1
# 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")

landplots_long.head(10)

# clean the year column to be numeric (e.g., 2023, 2024)
plot_id ecosystem_type treated year biomass
0 500 forest 1 biomass_2023 245.5
1 501 forest 1 biomass_2023 346.1
2 502 grassland 0 biomass_2023 604.1
3 503 forest 1 biomass_2023 452.0
4 504 forest 1 biomass_2023 329.5
5 505 grassland 0 biomass_2023 512.3
6 506 forest 1 biomass_2023 320.6
7 507 forest 0 biomass_2023 355.7
8 508 forest 0 biomass_2023 308.1
9 509 grassland 1 biomass_2023 420.5
# 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 = year

  • y = biomass

  • hue = 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 value

  • values: 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()