Title: Apply Functions By Group In Pandas
Slug: pandas_apply_function_by_group
Summary: Apply Functions By Group In Pandas
Date: 2016-05-01 12:00
Category: Python
Tags: Data Wrangling
Authors: Chris Albon
In [5]:
# import pandas as pd
import pandas as pd
In [6]:
# Create an example dataframe
data = {'Platoon': ['A','A','A','A','A','A','B','B','B','B','B','C','C','C','C','C'],
'Casualties': [1,4,5,7,5,5,6,1,4,5,6,7,4,6,4,6]}
df = pd.DataFrame(data)
df
Out[6]:
In [7]:
# Group df by df.platoon, then apply a rolling mean lambda function to df.casualties
df.groupby('Platoon')['Casualties'].apply(lambda x:x.rolling(center=False,window=2).mean())
Out[7]: