B13: Tidy data and split-apply-combine


[1]:
# Colab setup ------------------
import os, sys
if "google.colab" in sys.modules:
    data_path = "https://biocircuits.github.io/chapters/data/"
else:
    data_path = "data/"
# ------------------------------

import numpy as np
import pandas as pd

In the last lesson, we learned about Pandas and dipped our toe in to see its power. In this lesson, we will continue to harness the power of Pandas to pull out subsets of data we are interested in.

Tidy data

Hadley Wickham wrote a great article in favor of “tidy data.” Tidy data frames follow the rules:

  1. Each variable is a column.

  2. Each observation is a row.

  3. Each type of observation has its own separate data frame.

This is less pretty to visualize as a table, but we rarely look at data in tables. Indeed, the representation of data which is convenient for visualization is different from that which is convenient for analysis. A tidy data frame is almost always much easier to work with than non-tidy formats.

You may raise some objections about tidy data. Here are a few, and my responses.

Objection: Looking at a table of tidy data is ugly. It is not intuitively organized. I would almost never display a tidy data table in a publication.

Response: Correct! Having tabular data in a format that is easy to read as a human studying a table is a very different thing than having it in a format that is easy to explore and work with using a computer. As Daniel Chen put it, “There are data formats that are better for reporting and data formats that are better for analysis.” We are using the tidy data frames for analysis, not reporting (though we will see in the coming lessons that having the data in a tidy format makes making plots much easier, and plots are a key medium for reporting.)

Objection: Isn’t it better to sometimes have data arranged in other ways? Say in a matrix?

Response: This is certainly true for things like images, or raster-style data in general. It makes more sense to organize an image in a 2D matrix than to have it organized as a data frame with three columns (row in image, column in image, intensity of pixel), where each row corresponds to a single pixel. For an image, indexing it by row and column is always unambiguous, my_image[i, j] means the pixel at row i and column j.

For other data, though, the matrix layout suffers from the fact that there may be more than one way to construct a matrix. If you know a data frame is tidy, you already know its structure. You need only to ask what the columns are, and then you immediately know how to access data using Boolean indexing. In other formats, you might have to read and write extensive comments to understand the structure of the data. Of course, you can read and write comments, but it opens the door for the possibility of misinterpretation or mistakes.

Objection: But what about time series? Clearly, that can be in matrix format. One column is time, and then subsequent columns are observations made at that time.

Response: Yes, that is true. But then the matrix-style described could be considered tidy, since each row is a single observation (time point) that has many facets.

Objection: Isn’t this an inefficient use of memory? There tend to be lots of repeated entries in tidy data frames.

Response: Yes, there are more efficient ways of storing and accessing data. But for data sets that are not “big data,” this is seldom a real issue. The extra expense in memory, as well as the extra expense in access, are small prices to pay for the simplicity and speed of the human user in accessing the data.

Objection: Once it’s tidy, we pretty much have to use Boolean indexing to get what we want, and that can be slower than other methods of accessing data. What about performance?

Response: See the previous response. Speed of access really only becomes a problem with big, high-throughput data sets. In those cases, there are often many things you need to be clever about beyond organization of your data.

Conclusion: I really think that tidying a data set allows for fluid exploration. We will focus on tidy data sets going forward. The techniques for bringing untidy data into tidy format use many of Pandas’s functions, but are largely beyond the scope of this bootcamp. You will explore that a little bit in the exercises, but for most of the bootcamp, our data sets are already tidy.

The data set

We will use the same data set as in the previous section.

[2]:
df = pd.read_csv(os.path.join(data_path, "elowitz_et_al_2002_fig_3a.csv"))

# Take a look
df.head()
[2]:
strain CFP YFP
0 m22 2438 1409
1 m22 2316 1391
2 m22 2521 1511
3 m22 2646 1460
4 m22 2830 1638

This data set is in tidy format. Each row represents a measurement of a single cell. Each cell is from a specific strain and has an associated CFP and YFP fluorescent intensity. We already saw the power of having the data in this format when we did Boolean indexing in the last lesson. Now, we will see how this format allows use to easily do an operation we do again and again with data sets, split-apply-combine.

Split-apply-combine

Let’s say we want to compute the median CFP intensity separately for the m22 and d22 strains. Ignoring for the second the mechanics of how we would do this with Python, let’s think about it in English. What do we need to do?

  1. Split the data set up according to the 'strain' field, i.e., split it up so we have a separate data set for the two classes.

  2. Apply a median function to the activity in these split data sets.

  3. Combine the results of these averages on the split data set into a new, summary data set that contains the two classes and medians for each.

We see that the strategy we want is a split-apply-combine strategy. This idea was put forward by Hadley Wickham in this paper. It turns out that this is a strategy we want to use very often. Split the data in terms of some criterion. Apply some function to the split-up data. Combine the results into a new data frame.

Note that if the data are tidy, this procedure makes a lot of sense. Choose the column you want to use to split by. All rows with like entries in the splitting column are then grouped into a new data set. You can then apply any function you want into these new data sets. You can then combine the results into a new data frame.

Pandas’s split-apply-combine operations are achieved using the groupby() method. You can think of groupby() as the splitting part. You can then apply functions to the resulting DataFrameGroupBy object. The Pandas documentation on split-apply-combine is excellent and worth reading through. It is extensive though, so don’t let yourself get intimidated by it.

Aggregation: Median percent correct

Let’s go ahead and do our first split-apply-combine on this tidy data set. First, we will split the data set up by strain.

[3]:
grouped = df.groupby("strain")

# Take a look
grouped
[3]:
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x7fc529145e20>

There is not much to see in the DataFrameGroupBy object that resulted. But there is a lot we can do with this object. Typing grouped. and hitting tab will show you the many possibilities. For most of these possibilities, the apply and combine steps happen together and a new data frame is returned. The grouped.median() method is exactly what we want.

[4]:
df_median = grouped.median()

# Take a look
df_median
[4]:
CFP YFP
strain
d22 2646.0 1869.5
m22 2597.5 1414.0

The outputted data frame has the medians of all quantities, including the CFP intensity that we wanted. Note that this data frame has strain as the name of the row index. If we want to instead keep strain (which, remember, is what we used to split up the data set before we computed the summary statistics) as a column, we can use the reset_index() method.

[5]:
df_median.reset_index()
[5]:
strain CFP YFP
0 d22 2646.0 1869.5
1 m22 2597.5 1414.0

Note, though, that this was not done in-place. df_median still has an index labeled 'strain'. If you want to update your data frame, you have to explicitly do so with an assignment operator.

[6]:
df_median = df_median.reset_index()

This type of operation is called an aggregation. That is, we split the data set up into groups, and then computed a summary statistic for each group, in this case the median.

Transformation

Instead of summarizing data in a group with single summary statistics by aggregation, we can also do a transformation in which each row gets a new entry within a given group. As a simple example, we could generate a column that gives the rank of each cell in terms of CFP intensity for each strain. That is, we perform a rank ordering within the m22 strain and within the d22 strain.

[7]:
grouped['CFP'].rank()
[7]:
0       53.5
1       24.0
2       85.0
3      145.5
4      219.0
       ...
529     27.0
530     25.0
531     41.0
532    183.0
533     10.0
Name: CFP, Length: 534, dtype: float64

This gave us a column of ranks with the indexing of the original data frame preserved. We can put this column into the data frame.

[8]:
df['rank grouped by strain'] = grouped['CFP'].rank(method='first')

# Take a look
df.head()
[8]:
strain CFP YFP rank grouped by strain
0 m22 2438 1409 53.0
1 m22 2316 1391 24.0
2 m22 2521 1511 85.0
3 m22 2646 1460 145.0
4 m22 2830 1638 219.0

To verify that this worked correctly, and also to show some nice sorting properties of data frames, we will sort the data frame by strain and then by CFP and make sure the ranks worked accordingly.

[9]:
df_sorted = df.sort_values(by=["strain", "CFP"])

# Take a look
df_sorted
[9]:
strain CFP YFP rank grouped by strain
420 d22 1868 1564 1.0
290 d22 1882 1833 2.0
377 d22 1883 1707 3.0
291 d22 1890 1474 4.0
287 d22 1908 1506 5.0
... ... ... ... ...
42 m22 2933 1479 246.0
91 m22 2947 1486 247.0
205 m22 2951 1514 248.0
201 m22 2963 1509 249.0
189 m22 3023 1568 250.0

534 rows × 4 columns

Indeed it worked!

Aggregating and transforming with custom functions

Let’s say we want to compute the coefficient of variation (CoV, the standard deviation divided by the mean) of data in columns of groups in the data frame. There is no built-in function to do this. We have to write our own function to compute the CoV and then use it with the agg() method of a DataFrameGroupBy object. In the function below, the values of each column are denoted by data.

To compute the coefficient of variation, we will use one more Numpy function beyond np.mean() that you have already seen, np.std().

[10]:
def coeff_of_var(data):
    """Compute coefficient of variation from an array of data."""
    return np.std(data) / np.mean(data)

Now we can apply it as an aggregating function, omitting the 'strain' column because it is categorical and we cannot compute aggregate statistics.

[11]:
cols = df.columns[(df.columns != "strain") & (df.columns != "rank grouped by strain")]
grouped[cols].agg(coeff_of_var)
[11]:
CFP YFP
strain
d22 0.116101 0.113380
m22 0.073768 0.080851

Looping over a GroupBy object

While the GroupBy methods we have learned so far (like transform() and agg()) are useful and lead to concise code, we sometimes want to loop over the groups of a GroupBy object. This often comes up in plotting applications. As an example, I will compute the mean CFP fluorescent intensity for each strain.

[12]:
for strain, group in df.groupby("strain"):
    print(strain, ': ', group["CFP"].median())
d22 :  2646.0
m22 :  2597.5

By using the GroupBy object as an iterator, it yields the name of the group (which I assigned as strain) and the corresponding sub-data frame (which I assigned group).

Normalizing the intensities

With all of these skills in place, let us now do a useful calculation and normalize the fluorescent intensities for each fluorophore in each strain.

[13]:
# group_keys = False necessary keep index of original df
df[["norm CFP", "norm YFP"]] = df.groupby("strain", group_keys=False)[
    ["CFP", "YFP"]
].apply(lambda x: x / x.mean())

df.head()
[13]:
strain CFP YFP rank grouped by strain norm CFP norm YFP
0 m22 2438 1409 53.0 0.940376 1.000676
1 m22 2316 1391 24.0 0.893319 0.987892
2 m22 2521 1511 85.0 0.972390 1.073117
3 m22 2646 1460 145.0 1.020605 1.036896
4 m22 2830 1638 219.0 1.091577 1.163313

Computing environment

[14]:
%load_ext watermark
%watermark -v -p numpy,pandas,jupyterlab
Python implementation: CPython
Python version       : 3.9.16
IPython version      : 8.10.0

numpy     : 1.23.5
pandas    : 1.5.3
jupyterlab: 3.5.3