2024-heraklion-data/notebooks/030_tabular_data/031_split-apply-combine_tutor.ipynb
2024-08-27 15:27:53 +03:00

8.4 KiB

Split-apply-combine operations for tabular data

In [1]:
import pandas as pd
In [2]:
data = pd.DataFrame(
    data=[
        ['312', 'A1', 0.12, 'LEFT'],
        ['312', 'A2', 0.37, 'LEFT'],
        ['312', 'C2', 0.68, 'LEFT'],
        ['313', 'A1', 0.07, 'RIGHT'],
        ['313', 'B1', 0.08, 'RIGHT'],
        ['314', 'A2', 0.29, 'LEFT'],
        ['314', 'B1', 0.14, 'RIGHT'],
        ['314', 'C2', 0.73, 'RIGHT'],
        ['711', 'A1', 4.01, 'RIGHT'],
        ['712', 'A2', 3.29, 'LEFT'],
        ['713', 'B1', 5.74, 'LEFT'],
        ['714', 'B2', 3.32, 'RIGHT'],
    ],
    columns=['subject_id', 'condition_id', 'response_time', 'response'],
)
data
Out[2]:
subject_id condition_id response_time response
0 312 A1 0.12 LEFT
1 312 A2 0.37 LEFT
2 312 C2 0.68 LEFT
3 313 A1 0.07 RIGHT
4 313 B1 0.08 RIGHT
5 314 A2 0.29 LEFT
6 314 B1 0.14 RIGHT
7 314 C2 0.73 RIGHT
8 711 A1 4.01 RIGHT
9 712 A2 3.29 LEFT
10 713 B1 5.74 LEFT
11 714 B2 3.32 RIGHT

Group-by

We want to compute the mean response time by condition.

Let's start by doing it by hand, using for loops!

In [ ]:

In [ ]:

This is a basic operation, and we would need to repeat his pattern a million times!

Pandas and all other tools for tabular data provide a command for performing operations on groups.

In [ ]:

In [ ]:

Pivot tables

We want to look at response time biases when the subjects respond LEFT vs RIGHT. In principle, we expect them to have the same response time in both cases.

We compute a summary table with 1) condition_id on the rows; 2) response on the columns; 3) the average response time for all experiments with a that condition and response

We can do it with groupby, with some table manipulation commands.

In [ ]:

In [ ]:

Pandas has a command called pivot_table that can be used to perform this kind of operation straightforwardly.

In [ ]:

In [ ]:

In [ ]: