How it works...

The resample method, by default, works implicitly with a DatetimeIndex, which is why we set it to REPORTED_DATE in step 1. In step 2, we created an intermediate object that helps us understand how to form groups within the data. The first parameter to resample is the rule determining how the Timestamps in the index will be grouped. In this instance, we use the offset alias W to form groups one week in length ending on Sunday. The default ending day is Sunday, but may be changed with an anchored offset by appending a dash and the first three letters of a day of the week.

Once we have formed groups with resample, we must chain a method to take action on each of them. In step 3, we use the size method to count the number of crimes per week. You might be wondering what are all the possible attributes and methods available to use after calling resample. The following examines the resample object and outputs them:

>>> r = crime_sort.resample('W')
>>> resample_methods = [attr for attr in dir(r) if attr[0].islower()]
>>> print(resample_methods)
['agg', 'aggregate', 'apply', 'asfreq', 'ax', 'backfill', 'bfill', 'count', 'ffill', 'fillna', 'first', 'get_group', 'groups', 'indices', 'interpolate', 'last', 'max', 'mean', 'median', 'min', 'ndim', 'ngroups', 'nunique', 'obj', 'ohlc', 'pad', 'plot', 'prod', 'sem', 'size', 'std', 'sum', 'transform', 'var']

Step 4 verifies the accuracy of the count from step 3 by manually slicing the data by week and counting the number of rows. The resample method is actually not even necessary to group by Timestamp as the functionality is available directly from the groupby method itself. However, you must pass an instance of pd.Grouper to the groupby method using the freq parameter for the offset, as done in step 6.

A very similar object called pd.TimeGrouper is capable of grouping by time in the exact same fashion as pd.Grouper, but as of pandas version 0.21 it is deprecated and should not be used. Unfortunately, there are many examples online that use pd.TimeGrouper but do not let them tempt you.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.241.250