(c) 2016 Justin Bois. This work is licensed under a Creative Commons Attribution License CC-BY 4.0. All code contained herein is licensed under an MIT license.
This tutorial was generated from a Jupyter notebook. You can download the notebook here.
import numpy as np
import pandas as pd
Pandas can be a bit frustrating during your first experiences with it. In this lesson, we will practice using Pandas. The more and more you use it, the more distant the memory of life without it.
loc
¶We will again use the frog tongue adhesion data set. Your goal here is to extract certain entries out of the DataFrame
. If it is not in your namespace, load in the DataFrame
using pd.read_csv()
.
df = pd.read_csv('data/frog_tongue_adhesion.csv', comment='#')
a) Extract the impact time of all impacts that had an adhesive strength of magnitude greater than 2000 Pa.
b) Extract the impact force and adhesive force for all of Frog II's strikes.
c) Extract the adhesive force and the time the frog pulls on the target for juvenile frogs (Frogs III and IV).
# a) impact times for frogs with |adh. strenght| < 2000.
df.loc[np.abs(df['adhesive strength (Pa)'])<2000, 'impact time (ms)']
# b) Impact force and adhesive force for Frog II
df.loc[df['ID']=='II', ['impact force (mN)', 'adhesive force (mN)']]
# c) Adhesive force and time frog pulls for forgs III and IV
df.loc[df['ID'].isin(['III', 'IV']),
['adhesive force (mN)', 'time frog pulls on target (ms)']]
groupby()
¶The groupby()
method is one of the most powerful methods of Pandas DataFrame
s. It works by splitting up a DataFrame
based on some criterion. Once that happens, we can then apply a function to these split up DataFrame
. Upon application of the function, we get a recombined DataFrame
with the result.
This is best shown by example. The goal is to compute the mean impact force of each frog. First, do it the "long way."
- Extract all of Frog I's impact forces and compute the mean.
- Do the same for the other three frogs.
- Write a
for
loop to do this and return a NumPy array with the four mean impact forces.
Now, unfortunately, you don't get a DataFrame
out of this. You only get a NumPy array. But if you use groupby()
, you do. I'll show how it works by example.
# We only want ID's and impact forces, so slice those out
df_impf = df.loc[:, ['ID', 'impact force (mN)']]
# Make a GroupBy object
grouped = df_impf.groupby('ID')
# Apply the np.mean function to the grouped object
df_mean_impf = grouped.apply(np.mean)
# Look at the new DataFrame
df_mean_impf
Sweet! Look at that! We have a DataFrame
with the results. We can pull the mean impact force for a frog of interest using loc
.
df_mean_impf.loc['III', :]
Now, what is we want more information, like both the mean and the median? We can apply multiple functions to a GroupBy
object using the agg()
method. The argument of this method is a list of functions you want to apply.
grouped.agg([np.mean, np.median])
Now, let's practice with groupby()
.
a) Compute standard deviation of the impact forces for each frog.
b) Write a function, coeff_of_var(data)
, which computes the coefficient of variation of a data set. This is the standard deviation divided by the absolute value of the mean.
c) Compute coefficient of variation of the impact forces and adhesive forces for each frog.
d) And now, finally.... Compute a DataFrame
that has the mean, median, standard deviation, and coefficient of variation of the impact forces and adhesive forces for each frog.
# a) standard deviation of impact forces
grouped.apply(np.std)
# b and c: coeff. of variation for impact and adhesive force
def coeff_of_var(data):
"""Coefficient of variation."""
return np.std(data) / np.abs(np.mean(data))
# Make GroupBy object with two columns of interest in DataFrame
grouped = df[['ID', 'impact force (mN)', 'adhesive force (mN)']].groupby('ID')
# Applot te coeff_of_var_function
grouped.apply(coeff_of_var)
# d) Apply all of the great stats functions!
df_result = grouped.agg([np.mean, np.median, np.std, coeff_of_var])
df_result
Notice that this DataFrame
now has a MultiColumn
, i.e., we need to specify two things to select a column. The mean impact forces are:
df_result.loc[:, ('impact force (mN)', 'mean')]
If we just want the mean impact force and and mean adhesive force, we do this:
df_result.loc[:, (('impact force (mN)', 'adhesive force (mN)'), 'mean')]
And finally, if we want to make our results DataFrame
tidy, we do this:
# First make the index (frog ID) real part of DataFrame
df_result['ID'] = df_result.index
# Melt the DataFrame to make it tidy
pd.melt(df_result, var_name=['quantity', 'statistic'], id_vars='ID')