Pivot tables

Pivot tables#

For analysing data in groups, it may make sense to turn it into a Pivot table.

import pandas as pd
df = pd.DataFrame(
    {
        "cell": ["Purkinje","Purkinje","Purkinje","Purkinje","Purkinje"],
        "location": ["brain1", "brain1", "brain2", "brain2", "brain1"],
        "spikes": ["simple", "complex", "simple", "complex", "simple"],
        "value": [3.3, 5.1, 2.5, 6.2, 2.8],
    }
)

df
cell location spikes value
0 Purkinje brain1 simple 3.3
1 Purkinje brain1 complex 5.1
2 Purkinje brain2 simple 2.5
3 Purkinje brain2 complex 6.2
4 Purkinje brain1 simple 2.8

You can turn your table into a pivot table, for example by computing the mean of columns for elements in groups using pandas.pivot_table()

pivot = pd.pivot_table(
    df, values="value", index=["cell", "location"], columns=["spikes"], aggfunc="mean"
)
pivot
spikes complex simple
cell location
Purkinje brain1 5.1 3.05
brain2 6.2 2.50