---
title: "Data Wrangling"
description: |
This lesson focuses on wrangling linked datasets with `pandas`, including filtering, reordering, saving cleaned tables and merging DataFrames to prepare real data for analysis.
author:
- Noor Sohail
- Will Gammerdinger
date: "2026-03-16"
categories:
- Python programming
- Data wrangling
- Pandas
keywords:
- Data cleaning
- Merge DataFrames
- Save CSV
license: "CC-BY-4.0"
editor_options:
markdown:
wrap: 72
jupyter: intro_python
---
Approximate time: 70 minutes
## Learning objectives
In this lesson, we will:
- Reorder related datasets to ensure that they are in the same order
- Extract specific rows from a DataFrame using the `isin` function
- Save a DataFrame as a new CSV file
- Use the `merge()` function to combine two DataFrames
## Overview of lesson
Data wrangling is the step where messy, real‑world data is turned into something usable. In practice, this often means linking multiple tables (e.g., combining sample metadata with expression data), filtering out unwanted rows and then saving clean versions of your data for later use. `pandas` enables you to do all this and more. In this lesson, you will work with datasets and learn how to merge, filter and reorder tables so that you can easily complete downstream analyses and create visualizations.
## Linked DataFrames
Oftentimes, we have multiple files related to the same dataset. In these cases, we want to make sure that the data in these files are linked together in a way that allows us to match identities correctly. Therefore, knowing how to reorder datasets and determine data matches is an important skill.
In our use case, we will be working with genomic data. We have **gene expression data generated by RNA-seq** and metadata that corresponds to each samples. In our data folder, we have these two related files:
- `mouse_exp_design.csv`
- `counts.rpkm.csv`
### Read in expression data and metadata
Let’s start by reading in our gene expression data (RPKM matrix) and then previewing the first few lines:
```{python}
#| label: tbl-load_expression_data
#| tbl-cap: RPKM normalized expression data for 12 samples, where rows are genes and columns are samples.
# Import pandas using the alias pd
import pandas as pd
# Read in the gene expression data
rpkm_data = pd.read_csv("data/counts.rpkm.csv")
# Inspect the gene expression data to make sure it was read in properly
rpkm_data.head()
```
We will also read in a clean copy of the associated metadata file, since we do not need the extra columns we added earlier, and again preview the DataFrame:
```{python}
#| label: tbl-load_metadata
#| tbl-cap: Metadata for 12 samples, where rows are samples and columns are different attributes of the samples.
# Read in the metadata
metadata = pd.read_csv("data/mouse_exp_design.csv")
# Inspect the metadata to make sure it was read in properly
metadata.head()
```
It looks as if the sample names (header) in our data matrix are similar to the row names of our metadata file, but it’s hard to tell since they are not in the same order. We can do a quick check of the number of columns in the count data and the rows in the metadata and at least see if the numbers match up.
```{python}
#| label: check_dimensions
# Check the dimensions of the RPKM data
print("Dimensions of RPKM data:", rpkm_data.shape)
# Check the dimensions of the metadata
print("Dimensions of metadata:", metadata.shape)
```
We can see that we have 12 samples in both our expression data (columns) and our metadata (rows). What we want to know is, **are all the samples in our metadata also in our expression data?**
### The `isin` function
Let’s try checking if all our metadata samples are also in our expression data. We will use the `in` function to check for membership in a collection.
```{python}
#| label: get_sample_names
# Assign the rownames of the metadata DataFrame to x
x = metadata.index
# Assign the column names of the rpkm_data DataFrame to y
y = rpkm_data.columns
```
Now we can check to see if `x` are in `y`:
```{python}
#| label: check_membership
#| error: true
# Check if all elements of x are in y
x in y
```
We will get an error because we are not actually checking if a single element `x` can be found in `y`, but this code actually checks if the entire list of `x` is an element in `y`. Instead, the `isin` operator will actually check if each individual element of `x` is in `y`:
```{python}
#| label: check_membership_isin
# Check if each element of x is in y using isin
print(x.isin(y))
```
::: {.callout-note collapse="true"}
# List comprehension alternative to isin operator
There are many other ways to check for membership. One way is to use a list comprehension to check if each element of `x` is in `y` by iterating through the elements of each list and comparing each individual `x` and `y` to find membership:
```{python}
#| label: check_membership_list_comprehension
# Check if each element of x is in y
[sample in y for sample in x]
```
:::
If we have a large number of samples and are unable to count that each element of `x` is in `y`, we can instead use the `all()` function to check if all elements are `True`:
```{python}
#| label: check_all_membership
# Check if all elements of x are in y
all(x.isin(y))
```
So now we know that all of our samples in the metadata are also in our expression data, but we don't know if they in the same order. We can check the order of our data by comparing the order of `x` and `y`:
```{python}
#| label: check_order
# Check if the order of x and y is the same
print(x == y)
```
We can see that they are not in the same order. We can use the `reindex` method to reorder our expression data to match the order of our metadata:
```{python}
#| label: tbl-reorder_expression_data
#| tbl-cap: Reordered RPKM data columns to match the order of the metadata rownames.
# Reorder the columns of the rpkm_data DataFrame to match the order of the metadata
rpkm_ordered = rpkm_data.reindex(columns = metadata.index)
# Inspect the re-ordered table to make sure it looks correct
rpkm_ordered.head()
```
When we look at the columns of `rpkm_ordered` now, we see that they are now in the same order as the row names of our metadata (numerical order).
:::{.callout-tip}
# [**Exercise 1**](10_data_wrangling-Answer_key.qmd#exercise-1)
We have a list of 6 marker genes that we are interested in. Our goal is to extract count data for these genes using the `isin` operator from the `rpkm_ordered` DataFrame instead of finding them manually.
First, we will create a list called `important_genes` with the Ensemble IDs of the 6 genes we are interested in:
```{python}
#| label: create_important_genes
# Create important genes list
important_genes = ["ENSMUSG00000083700", "ENSMUSG00000080990",
"ENSMUSG00000065619", "ENSMUSG00000047945",
"ENSMUSG00000081010", "ENSMUSG00000030970"]
```
1. Use the `isin` operator to determine which row names of the `rpkm_ordered` DataFrame match our genes of interest.
2. Extract the rows from `rpkm_ordered` that correspond to these 6 genes by using `[]` and the `isin` operator. Double check the row names to ensure that you are extracting the correct rows.
3. **Bonus question:** Extract the rows from `rpkm_ordered` that correspond to these 6 genes using `[]`, but without using the `isin` operator. Do you notice anything different about the output?
:::
## Saving CSV files
Now that we have our properly ordered expression data, we will save it as a new CSV file by using the `to_csv` method:
```{python}
#| label: save_csv
# Save the reordered expression data to a new CSV file
rpkm_ordered.to_csv("data/ordered_counts_rpkm.csv")
```
So if we wanted to read in this new file, we can use the `read_csv` method:
```{python}
#| label: tbl-read_new_csv
#| tbl-cap: Read in the new CSV file that of the ordered RPKM data that was just saved.
# Read in the new CSV file
rpkm_ordered_new = pd.read_csv("data/ordered_counts_rpkm.csv")
# Inspect the read-in CSV file
rpkm_ordered_new.head()
```
If you look at the output, you'll see an extra column called `Unnamed: 0`. This is because when we loaded in the CSV file, the index (rownames) were not set. Instead, they were read in as a regular column without a row name. When we load in our new CSV file, we want to set the first column as the index to ensure that the genes are being stored as row names:
```{python}
#| label: tbl-read_new_csv_rownames
#| tbl-cap: Read in the new CSV file that of the ordered RPKM data that was just saved with rownames set appropriately.
# Read in the new CSV file with genes as rownames
rpkm_ordered_new = pd.read_csv("data/ordered_counts_rpkm.csv",
index_col = 0)
# Inspect the read-in CSV file
rpkm_ordered_new.head()
```
## Wrangling DataFrames
Now we want to update some information in our `metadata` object. We want to evaluate the average expression for each sample and its relationship with the age of the mouse. Our goal is to wrangle our data so we can create visualizations with these new columns in the next lesson.
### Calculating average expression
Let’s take a closer look at our counts data. Each column represents a sample in our experiment and each sample has ~38K values corresponding to the expression of different transcripts. We want to compute the **average value of expression** for each sample.
Taking this one step at a time, what would we do if we just wanted the average expression for Sample 1 across all genes. We can use the base `numpy` function called `mean()`:
```{python}
#| label: calculate_mean_sample_1
# Import numpy using the alias np
import numpy as np
# Take the mean of the expression values for sample1
print(np.mean(rpkm_ordered["sample1"]))
```
This gives us the average from one of the samples (one column in a DataFrame), but we need to get this information from all 12 samples (therefore all columns). Ideally, we want a list of 12 values that we can easily add to the metadata DataFrame. What is the best way to do this?
Luckily, the `pandas` library has a built-in method called `mean()` that can be applied to a DataFrame. By default, it will calculate the mean of each column and return a new series with the mean values for each column:
```{python}
#| label: calculate_mean_all_samples
# Calculate the mean expression for each sample (column) in the rpkm_ordered DataFrame
samplemeans = rpkm_ordered.mean()
# Inspect samplemeans
samplemeans
```
We have now the values that we want, except notice they don't have a column name associated with these results. We can use the `name` attribute to assign a name to this series:
```{python}
#| label: name_samplemeans
# Name the samplemeans series
samplemeans.name = "mean_expression"
# Inspect samplemeans
samplemeans
```
### Merging DataFrames
At this point, `samplemeans` is a series object with the sample names as the index and the mean expression values as the corresponding values. Next we will add this information to our `metadata` DataFrame. One of the most straightforward ways to do so is to use the `merge()` method from the `pandas` library, which allows us to merge two DataFrames by using a common column or index.
Since this is a new method, we will use the `help()` function to learn more about it:
```{python}
#| label: help_merge
#| eval: false
# Get help on the merge function
help(pd.merge)
```
When we look at the arguments for the `merge()` method, we can see that we can specify the left and right DataFrames to merge, as well as the columns or indices we want to merge on. We can specify what columns or indices to merge on using the `left_*` and `right_*` arguments.
In this case, the "left" DataFrame will be the `metadata` and the "right" DataFrame will be the `samplemeans`. Since both `metadata` and `samplemeans` have the sample names as indicies, we can merge them on the indices using the `left_index` and `right_index` arguments:
```{python}
#| label: merge_dataframes
#| error: true
# Merge the samplemeans series with the metadata DataFrame on the index
new_metadata = metadata.merge(samplemeans,
left_index = True,
right_index = True)
# Inspect the merged metadata
new_metadata.head()
```
Now we have a left-joined `new_metadata` with all the information from the original metadata as well as a new column with the mean expression values for each sample.
This means merging can be done with any two DataFrames that have a common column or index and it is a very powerful tool for combining information from different sources.
### Adding an `age` column
Let’s also create a list with the ages of each of the mice in our dataset. We also want to ensure that we have 12 values in this list to match the 12 samples in our data set. In this example we are supplying the ages manually, but in a real use case, we would likely have this information in a separate file that we would read in and merge with our metadata DataFrame using the `merge()` function as we just did with the `samplemeans` series.
```{python}
#| label: add_age_column
# Add the age column to the metadata DataFrame
# Create a numeric list with ages.
age_in_days = [40, 32, 38, 35, 41, 32,
34, 26, 28, 28, 30, 32]
# Double check that we have 12 values, 1 for each sample
len(age_in_days)
```
Now we will create a new column in our `new_metadata` DataFrame called `age` and assign the values from our `age_in_days` list to the new column:
```{python}
#| label: assign_age_column
# Assign the age_in_days list to a new column in new_metadata
new_metadata["age_in_days"] = age_in_days
# Inspect new_metadata to ensure the age column was appended correctly
new_metadata.head()
```
Now that we have the data in the format that we want, we will save the new metadata DataFrame as a new CSV file using the `to_csv()` method:
```{python}
#| label: save_new_metadata
# Save the new metadata DataFrame to a new CSV file
new_metadata.to_csv("data/new_metadata.csv")
```
**We are now ready for plotting and data visualization!**
## Fun with data wrangling
As you work more and more with different datasets, you will likely find yourself spending a lot of time and energy wrangling data to put it in the right format for analysis. We have a few fun and useful exercises to practice some of the data wrangling skills we have learned in this lesson.
::: {.callout-tip}
# [**Exercise 2**](10_data_wrangling-Answer_key.qmd#exercise-2)
**Reading in and inspecting data**
1. Using the `animals.csv` within your `data` directory, read the `.csv` file into your environment and assign it to a variable called `animals`. _Be sure to check that your row names are the different animals._
2. Check to make sure that `animals` is a DataFrame.
3. How many rows are in the `animals` DataFrame? How many columns?
**Data wrangling**
4. Extract the `speed` value of 40 km/h from the `animals` DataFrame.
5. Return the rows with animals that are the `color` Tan.
6. Return the rows with animals that have `speed` greater than 50 km/h and output only the `color` column. Keep the output as a DataFrame.
7. Change the color of "Grey" to "Gray".
8. Create a list called `animals_list` in which the first element contains the speed column of the `animals` DataFrame and the second element contains the color column of the `animals` DataFrame.
9. Create a dictionary with the appropriate keys (i.e., speed and color).
**The `isin` operator, reordering and matching**
10. In the `data` directory, you should have a table called `project-summary.txt` that contains quality metric information for an RNA-seq dataset. We have obtained batch information for the control samples in this dataset. _Copy and paste the code below to create DataFrames for the project summary and for the control samples with the associated batch information_:
```{python}
#| label: create_ctrl_samples_df
# Read in proj_summary
proj_summary = pd.read_table("data/project-summary.txt",
header=0, index_col=0)
# Create ctrl_samples dataframe
ctrl_samples = pd.DataFrame(
data = {"date": ["01/13/2018", "03/15/2018", "01/13/2018",
"09/20/2018","03/15/2018"]},
index = ["sample3", "sample10", "sample8",
"sample4", "sample15"])
```
```{python}
#| label: tbl-proj_summary
#| tbl-cap: DataFrame of quality metric information for an RNA-seq dataset.
# View RNA-seq QC information
proj_summary
```
```{python}
#| label: tbl-ctrl_samples
#| tbl-cap: DataFrame of control samples with associated batch information.
# View control batch information
ctrl_samples
```
11. How many of the `ctrl_samples` are also in the `proj_summary` DataFrame? Use the `isin` operator to compare sample names.
12. Keep only the rows in `proj_summary` which correspond to those in `ctrl_samples`. Do this with the `isin` operator. Save it to a variable called `proj_summary_ctrl`.
13. Use `merge()` to add a column called `batch` to the `proj_summary_ctrl` DataFrame. Assign this new DataFrame back to `proj_summary_ctrl`.
:::
***
[Next Lesson >>](11_plotting_basics.qmd)
[Back to Schedule](../schedule/schedule.qmd)