groupby
Group By: split-apply-combine
By “group by” we are referring to a process involving one or more of the following
steps:
- Splitting the data into groups based on some criteria.
- Applying a function to each group independently.
- Combining the results into a data structure.
Out of these, the split step is the most straightforward. In fact, in many
situations we may wish to split the data set into groups and do something with
those groups. In the apply step, we might wish to do one of the
following:
Aggregation: compute a summary statistic (or statistics) for each
group. Some examples:- Compute group sums or means.
- Compute group sizes / counts.
Transformation: perform some group-specific computations and return a
like-indexed object. Some examples:- Standardize data (zscore) within a group.
- Filling NAs within groups with a value derived from each group.
Filtration: discard some groups, according to a group-wise computation
that evaluates True or False. Some examples:- Discard data that belongs to groups with only a few members.
- Filter out data based on the group sum or mean.
Some combination of the above: GroupBy will examine the results of the apply
step and try to return a sensibly combined result if it doesn’t fit into
either of the above two categories.
Since the set of object instance methods on pandas data structures are generally
rich and expressive, we often simply want to invoke, say, a DataFrame function
on each group. The name GroupBy should be quite familiar to those who have used
a SQL-based tool (or itertools), in which you can write code like:
1 | SELECT Column1, Column2, mean(Column3), sum(Column4) |
We aim to make operations like this natural and easy to express using
pandas. We’ll address each area of GroupBy functionality then provide some
non-trivial examples / use cases.
See the cookbook for some advanced strategies.
Splitting an object into groups
pandas objects can be split on any of their axes. The abstract definition of
grouping is to provide a mapping of labels to group names. To create a GroupBy
object (more on what the GroupBy object is later), you may do the following:
1 | In [1]: df = pd.DataFrame([('bird', 'Falconiformes', 389.0), |
The mapping can be specified many different ways:
- A Python function, to be called on each of the axis labels.
- A list or NumPy array of the same length as the selected axis.
- A dict or
Series, providing alabel -> group namemapping. - For
DataFrameobjects, a string indicating a column to be used to group.
Of coursedf.groupby('A')is just syntactic sugar fordf.groupby(df['A']), but it makes life simpler. - For
DataFrameobjects, a string indicating an index level to be used to
group. - A list of any of the above things.
Collectively we refer to the grouping objects as the keys. For example,
consider the following DataFrame:
::: tip Note
A string passed to groupby may refer to either a column or an index level.
If a string matches both a column name and an index level name, aValueError will be raised.
:::
1 | In [6]: df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', |
On a DataFrame, we obtain a GroupBy object by calling groupby().
We could naturally group by either the A or B columns, or both:
1 | In [8]: grouped = df.groupby('A') |
New in version 0.24.
If we also have a MultiIndex on columns A and B, we can group by all
but the specified columns
1 | In [10]: df2 = df.set_index(['A', 'B']) |
These will split the DataFrame on its index (rows). We could also split by the
columns:
1 | In [13]: def get_letter_type(letter): |
pandas Index objects support duplicate values. If a
non-unique index is used as the group key in a groupby operation, all values
for the same index value will be considered to be in one group and thus the
output of aggregation functions will only contain unique index values:
1 | In [15]: lst = [1, 2, 3, 1, 2, 3] |
Note that no splitting occurs until it’s needed. Creating the GroupBy object
only verifies that you’ve passed a valid mapping.
::: tip Note
Many kinds of complicated data manipulations can be expressed in terms of
GroupBy operations (though can’t be guaranteed to be the most
efficient). You can get quite creative with the label mapping functions.
:::
GroupBy sorting
By default the group keys are sorted during the groupby operation. You may however pass sort=False for potential speedups:
1 | In [21]: df2 = pd.DataFrame({'X': ['B', 'B', 'A', 'A'], 'Y': [1, 2, 3, 4]}) |
Note that groupby will preserve the order in which observations are sorted within each group.
For example, the groups created by groupby() below are in the order they appeared in the original DataFrame:
1 | In [24]: df3 = pd.DataFrame({'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]}) |
GroupBy object attributes
The groups attribute is a dict whose keys are the computed unique groups
and corresponding values being the axis labels belonging to each group. In the
above example we have:
1 | In [27]: df.groupby('A').groups |
Calling the standard Python len function on the GroupBy object just returns
the length of the groups dict, so it is largely just a convenience:
1 | In [29]: grouped = df.groupby(['A', 'B']) |
GroupBy will tab complete column names (and other attributes):
1 | In [32]: df |
1 | In [34]: gb.<TAB> # noqa: E225, E999 |
GroupBy with MultiIndex
With hierarchically-indexed data, it’s quite
natural to group by one of the levels of the hierarchy.
Let’s create a Series with a two-level MultiIndex.
1 | In [35]: arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], |
We can then group by one of the levels in s.
1 | In [39]: grouped = s.groupby(level=0) |
If the MultiIndex has names specified, these can be passed instead of the level
number:
1 | In [41]: s.groupby(level='second').sum() |
The aggregation functions such as sum will take the level parameter
directly. Additionally, the resulting index will be named according to the
chosen level:
1 | In [42]: s.sum(level='second') |
Grouping with multiple levels is supported.
1 | In [43]: s |
New in version 0.20.
Index level names may be supplied as keys.
1 | In [45]: s.groupby(['first', 'second']).sum() |
More on the sum function and aggregation later.
Grouping DataFrame with Index levels and columns
A DataFrame may be grouped by a combination of columns and index levels by
specifying the column names as strings and the index levels as pd.Grouper
objects.
1 | In [46]: arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], |
The following example groups df by the second index level and
the A column.
1 | In [50]: df.groupby([pd.Grouper(level=1), 'A']).sum() |
Index levels may also be specified by name.
1 | In [51]: df.groupby([pd.Grouper(level='second'), 'A']).sum() |
New in version 0.20.
Index level names may be specified as keys directly to groupby.
1 | In [52]: df.groupby(['second', 'A']).sum() |
DataFrame column selection in GroupBy
Once you have created the GroupBy object from a DataFrame, you might want to do
something different for each of the columns. Thus, using [] similar to
getting a column from a DataFrame, you can do:
1 | In [53]: grouped = df.groupby(['A']) |
This is mainly syntactic sugar for the alternative and much more verbose:
1 | In [56]: df['C'].groupby(df['A']) |
Additionally this method avoids recomputing the internal grouping information
derived from the passed key.
Iterating through groups
With the GroupBy object in hand, iterating through the grouped data is very
natural and functions similarly to itertools.groupby():
1 | In [57]: grouped = df.groupby('A') |
In the case of grouping by multiple keys, the group name will be a tuple:
1 | In [59]: for name, group in df.groupby(['A', 'B']): |
Selecting a group
A single group can be selected usingget_group():
1 | In [60]: grouped.get_group('bar') |
Or for an object grouped on multiple columns:
1 | In [61]: df.groupby(['A', 'B']).get_group(('bar', 'one')) |
Aggregation
Once the GroupBy object has been created, several methods are available to
perform a computation on the grouped data. These operations are similar to the
aggregating API, window functions API,
and resample API.
An obvious one is aggregation via theaggregate() or equivalentlyagg() method:
1 | In [62]: grouped = df.groupby('A') |
As you can see, the result of the aggregation will have the group names as the
new index along the grouped axis. In the case of multiple keys, the result is a
MultiIndex by default, though this can be
changed by using the as_index option:
1 | In [66]: grouped = df.groupby(['A', 'B'], as_index=False) |
Note that you could use the reset_index DataFrame function to achieve the
same result as the column names are stored in the resulting MultiIndex:
1 | In [69]: df.groupby(['A', 'B']).sum().reset_index() |
Another simple aggregation example is to compute the size of each group.
This is included in GroupBy as the size method. It returns a Series whose
index are the group names and whose values are the sizes of each group.
1 | In [70]: grouped.size() |
1 | In [71]: grouped.describe() |
::: tip Note
Aggregation functions will not return the groups that you are aggregating over
if they are named columns, when as_index=True, the default. The grouped columns will
be the indices of the returned object.
Passing as_index=False will return the groups that you are aggregating over, if they are
named columns.
:::
Aggregating functions are the ones that reduce the dimension of the returned objects.
Some common aggregating functions are tabulated below:
| Function | Description |
|---|---|
| mean() | Compute mean of groups |
| sum() | Compute sum of group values |
| size() | Compute group sizes |
| count() | Compute count of group |
| std() | Standard deviation of groups |
| var() | Compute variance of groups |
| sem() | Standard error of the mean of groups |
| describe() | Generates descriptive statistics |
| first() | Compute first of group values |
| last() | Compute last of group values |
| nth() | Take nth value, or a subset if n is a list |
| min() | Compute min of group values |
| max() | Compute max of group values |
The aggregating functions above will exclude NA values. Any function which
reduces a Series to a scalar value is an aggregation function and will work,
a trivial example is df.groupby('A').agg(lambda ser: 1). Note thatnth() can act as a reducer or a
filter, see here.
Applying multiple functions at once
With grouped Series you can also pass a list or dict of functions to do
aggregation with, outputting a DataFrame:
1 | In [72]: grouped = df.groupby('A') |
On a grouped DataFrame, you can pass a list of functions to apply to each
column, which produces an aggregated result with a hierarchical index:
1 | In [74]: grouped.agg([np.sum, np.mean, np.std]) |
The resulting aggregations are named for the functions themselves. If you
need to rename, then you can add in a chained operation for a Series like this:
1 | In [75]: (grouped['C'].agg([np.sum, np.mean, np.std]) |
For a grouped DataFrame, you can rename in a similar manner:
1 | In [76]: (grouped.agg([np.sum, np.mean, np.std]) |
::: tip Note
In general, the output column names should be unique. You can’t apply
the same function (or two functions with the same name) to the same
column.
1 | In [77]: grouped['C'].agg(['sum', 'sum']) |
Pandas does allow you to provide multiple lambdas. In this case, pandas
will mangle the name of the (nameless) lambda functions, appending _
to each subsequent lambda.
1 | In [78]: grouped['C'].agg([lambda x: x.max() - x.min(), |
:::
Named aggregation
New in version 0.25.0.
To support column-specific aggregation with control over the output column names, pandas
accepts the special syntax in GroupBy.agg(), known as “named aggregation”, where
- The keywords are the output column names
- The values are tuples whose first element is the column to select
and the second element is the aggregation to apply to that column. Pandas
provides thepandas.NamedAggnamedtuple with the fields['column', 'aggfunc']
to make it clearer what the arguments are. As usual, the aggregation can
be a callable or a string alias.
1 | In [79]: animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'], |
pandas.NamedAgg is just a namedtuple. Plain tuples are allowed as well.
1 | In [82]: animals.groupby("kind").agg( |
If your desired output column names are not valid python keywords, construct a dictionary
and unpack the keyword arguments
1 | In [83]: animals.groupby("kind").agg(**{ |
Additional keyword arguments are not passed through to the aggregation functions. Only pairs
of (column, aggfunc) should be passed as **kwargs. If your aggregation functions
requires additional arguments, partially apply them with functools.partial().
::: tip Note
For Python 3.5 and earlier, the order of **kwargs in a functions was not
preserved. This means that the output column ordering would not be
consistent. To ensure consistent ordering, the keys (and so output columns)
will always be sorted for Python 3.5.
:::
Named aggregation is also valid for Series groupby aggregations. In this case there’s
no column selection, so the values are just the functions.
1 | In [84]: animals.groupby("kind").height.agg( |
Applying different functions to DataFrame columns
By passing a dict to aggregate you can apply a different aggregation to the
columns of a DataFrame:
1 | In [85]: grouped.agg({'C': np.sum, |
The function names can also be strings. In order for a string to be valid it
must be either implemented on GroupBy or available via dispatching:
1 | In [86]: grouped.agg({'C': 'sum', 'D': 'std'}) |
Cython-optimized aggregation functions
Some common aggregations, currently only sum, mean, std, and sem, have
optimized Cython implementations:
1 | In [87]: df.groupby('A').sum() |
Of course sum and mean are implemented on pandas objects, so the above
code would work even without the special versions via dispatching (see below).
Transformation
The transform method returns an object that is indexed the same (same size)
as the one being grouped. The transform function must:
- Return a result that is either the same size as the group chunk or
broadcastable to the size of the group chunk (e.g., a scalar,grouped.transform(lambda x: x.iloc[-1])). - Operate column-by-column on the group chunk. The transform is applied to
the first group chunk using chunk.apply. - Not perform in-place operations on the group chunk. Group chunks should
be treated as immutable, and changes to a group chunk may produce unexpected
results. For example, when usingfillna,inplacemust beFalse
(grouped.transform(lambda x: x.fillna(inplace=False))). - (Optionally) operates on the entire group chunk. If this is supported, a
fast path is used starting from the second chunk.
For example, suppose we wished to standardize the data within each group:
1 | In [89]: index = pd.date_range('10/1/1999', periods=1100) |
We would expect the result to now have mean 0 and standard deviation 1 within
each group, which we can easily check:
1 | # Original Data |
We can also visually compare the original and transformed data sets.
1 | In [101]: compare = pd.DataFrame({'Original': ts, 'Transformed': transformed}) |

Transformation functions that have lower dimension outputs are broadcast to
match the shape of the input array.
1 | In [103]: ts.groupby(lambda x: x.year).transform(lambda x: x.max() - x.min()) |
Alternatively, the built-in methods could be used to produce the same outputs.
1 | In [104]: max = ts.groupby(lambda x: x.year).transform('max') |
Another common data transform is to replace missing data with the group mean.
1 | In [107]: data_df |
We can verify that the group means have not changed in the transformed data
and that the transformed data contains no NAs.
1 | In [113]: grouped_trans = transformed.groupby(key) |
::: tip Note
Some functions will automatically transform the input when applied to a
GroupBy object, but returning an object of the same shape as the original.
Passing as_index=False will not affect these transformation methods.
For example: fillna, ffill, bfill, shift..
1 | In [119]: grouped.ffill() |
:::
New syntax to window and resample operations
New in version 0.18.1.
Working with the resample, expanding or rolling operations on the groupby
level used to require the application of helper functions. However,
now it is possible to use resample(), expanding() androlling() as methods on groupbys.
The example below will apply the rolling() method on the samples of
the column B based on the groups of column A.
1 | In [120]: df_re = pd.DataFrame({'A': [1] * 10 + [5] * 10, |
The expanding() method will accumulate a given operation
(sum() in the example) for all the members of each particular
group.
1 | In [123]: df_re.groupby('A').expanding().sum() |
Suppose you want to use the resample() method to get a daily
frequency in each group of your dataframe and wish to complete the
missing values with the ffill() method.
1 | In [124]: df_re = pd.DataFrame({'date': pd.date_range(start='2016-01-01', periods=4, |
Filtration
The filter method returns a subset of the original object. Suppose we
want to take only elements that belong to groups with a group sum greater
than 2.
1 | In [127]: sf = pd.Series([1, 1, 2, 3, 3, 3]) |
The argument of filter must be a function that, applied to the group as a
whole, returns True or False.
Another useful operation is filtering out elements that belong to groups
with only a couple members.
1 | In [129]: dff = pd.DataFrame({'A': np.arange(8), 'B': list('aabbbbcc')}) |
Alternatively, instead of dropping the offending groups, we can return a
like-indexed objects where the groups that do not pass the filter are filled
with NaNs.
1 | In [131]: dff.groupby('B').filter(lambda x: len(x) > 2, dropna=False) |
For DataFrames with multiple columns, filters should explicitly specify a column as the filter criterion.
1 | In [132]: dff['C'] = np.arange(8) |
::: tip Note
Some functions when applied to a groupby object will act as a filter on the input, returning
a reduced shape of the original (and potentially eliminating groups), but with the index unchanged.
Passing as_index=False will not affect these transformation methods.
For example: head, tail.
1 | In [134]: dff.groupby('B').head(2) |
:::
Dispatching to instance methods
When doing an aggregation or transformation, you might just want to call an
instance method on each data group. This is pretty easy to do by passing lambda
functions:
1 | In [135]: grouped = df.groupby('A') |
But, it’s rather verbose and can be untidy if you need to pass additional
arguments. Using a bit of metaprogramming cleverness, GroupBy now has the
ability to “dispatch” method calls to the groups:
1 | In [137]: grouped.std() |
What is actually happening here is that a function wrapper is being
generated. When invoked, it takes any passed arguments and invokes the function
with any arguments on each group (in the above example, the std
function). The results are then combined together much in the style of agg
and transform (it actually uses apply to infer the gluing, documented
next). This enables some operations to be carried out rather succinctly:
1 | In [138]: tsdf = pd.DataFrame(np.random.randn(1000, 3), |
In this example, we chopped the collection of time series into yearly chunks
then independently called fillna on the
groups.
The nlargest and nsmallest methods work on Series style groupbys:
1 | In [142]: s = pd.Series([9, 8, 7, 5, 19, 1, 4.2, 3.3]) |
Flexible apply
Some operations on the grouped data might not fit into either the aggregate or
transform categories. Or, you may simply want GroupBy to infer how to combine
the results. For these, use the apply function, which can be substituted
for both aggregate and transform in many standard use cases. However,apply can handle some exceptional use cases, for example:
1 | In [147]: df |
The dimension of the returned result can also change:
1 | In [150]: grouped = df.groupby('A')['C'] |
apply on a Series can operate on a returned value from the applied function,
that is itself a series, and possibly upcast the result to a DataFrame:
1 | In [153]: def f(x): |
::: tip Note
apply can act as a reducer, transformer, or filter function, depending on exactly what is passed to it.
So depending on the path taken, and exactly what you are grouping. Thus the grouped columns(s) may be included in
the output as well as set the indices.
:::
Other useful features
Automatic exclusion of “nuisance” columns
Again consider the example DataFrame we’ve been looking at:
1 | In [157]: df |
Suppose we wish to compute the standard deviation grouped by the A
column. There is a slight problem, namely that we don’t care about the data in
column B. We refer to this as a “nuisance” column. If the passed
aggregation function can’t be applied to some columns, the troublesome columns
will be (silently) dropped. Thus, this does not pose any problems:
1 | In [158]: df.groupby('A').std() |
Note that df.groupby('A').colname.std(). is more efficient thandf.groupby('A').std().colname, so if the result of an aggregation function
is only interesting over one column (here colname), it may be filtered
before applying the aggregation function.
::: tip Note
Any object column, also if it contains numerical values such as Decimal
objects, is considered as a “nuisance” columns. They are excluded from
aggregate functions automatically in groupby.
If you do wish to include decimal or object columns in an aggregation with
other non-nuisance data types, you must do so explicitly.
:::
1 | In [159]: from decimal import Decimal |
Handling of (un)observed Categorical values
When using a Categorical grouper (as a single grouper, or as part of multiple groupers), the observed keyword
controls whether to return a cartesian product of all possible groupers values (observed=False) or only those
that are observed groupers (observed=True).
Show all values:
1 | In [164]: pd.Series([1, 1, 1]).groupby(pd.Categorical(['a', 'a', 'a'], |
Show only the observed values:
1 | In [165]: pd.Series([1, 1, 1]).groupby(pd.Categorical(['a', 'a', 'a'], |
The returned dtype of the grouped will always include all of the categories that were grouped.
1 | In [166]: s = pd.Series([1, 1, 1]).groupby(pd.Categorical(['a', 'a', 'a'], |
NA and NaT group handling
If there are any NaN or NaT values in the grouping key, these will be
automatically excluded. In other words, there will never be an “NA group” or
“NaT group”. This was not the case in older versions of pandas, but users were
generally discarding the NA group anyway (and supporting it was an
implementation headache).
Grouping with ordered factors
Categorical variables represented as instance of pandas’s Categorical class
can be used as group keys. If so, the order of the levels will be preserved:
1 | In [168]: data = pd.Series(np.random.randn(100)) |
Grouping with a grouper specification
You may need to specify a bit more data to properly group. You can
use the pd.Grouper to provide this local control.
1 | In [171]: import datetime |
Groupby a specific column with the desired frequency. This is like resampling.
1 | In [174]: df.groupby([pd.Grouper(freq='1M', key='Date'), 'Buyer']).sum() |
You have an ambiguous specification in that you have a named index and a column
that could be potential groupers.
1 | In [175]: df = df.set_index('Date') |
Taking the first rows of each group
Just like for a DataFrame or Series you can call head and tail on a groupby:
1 | In [179]: df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B']) |
This shows the first or last n rows from each group.
Taking the nth row of each group
To select from a DataFrame or Series the nth item, usenth(). This is a reduction method, and
will return a single row (or no row) per group if you pass an int for n:
1 | In [184]: df = pd.DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B']) |
If you want to select the nth not-null item, use the dropna kwarg. For a DataFrame this should be either 'any' or 'all' just like you would pass to dropna:
1 | # nth(0) is the same as g.first() |
As with other methods, passing as_index=False, will achieve a filtration, which returns the grouped row.
1 | In [194]: df = pd.DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B']) |
You can also select multiple rows from each group by specifying multiple nth values as a list of ints.
1 | In [198]: business_dates = pd.date_range(start='4/1/2014', end='6/30/2014', freq='B') |
Enumerate group items
To see the order in which each row appears within its group, use thecumcount method:
1 | In [201]: dfg = pd.DataFrame(list('aaabba'), columns=['A']) |
Enumerate groups
New in version 0.20.2.
To see the ordering of the groups (as opposed to the order of rows
within a group given by cumcount) you can usengroup().
Note that the numbers given to the groups match the order in which the
groups would be seen when iterating over the groupby object, not the
order they are first observed.
1 | In [205]: dfg = pd.DataFrame(list('aaabba'), columns=['A']) |
Plotting
Groupby also works with some plotting methods. For example, suppose we
suspect that some features in a DataFrame may differ by group, in this case,
the values in column 1 where the group is “B” are 3 higher on average.
1 | In [209]: np.random.seed(1234) |
We can easily visualize this with a boxplot:
1 | In [213]: df.groupby('g').boxplot() |

The result of calling boxplot is a dictionary whose keys are the values
of our grouping column g (“A” and “B”). The values of the resulting dictionary
can be controlled by the return_type keyword of boxplot.
See the visualization documentation for more.
::: danger Warning
For historical reasons, df.groupby("g").boxplot() is not equivalent
to df.boxplot(by="g"). See here for
an explanation.
:::
Piping function calls
New in version 0.21.0.
Similar to the functionality provided by DataFrame and Series, functions
that take GroupBy objects can be chained together using a pipe method to
allow for a cleaner, more readable syntax. To read about .pipe in general terms,
see here.
Combining .groupby and .pipe is often useful when you need to reuse
GroupBy objects.
As an example, imagine having a DataFrame with columns for stores, products,
revenue and quantity sold. We’d like to do a groupwise calculation of prices
(i.e. revenue/quantity) per store and per product. We could do this in a
multi-step operation, but expressing it in terms of piping can make the
code more readable. First we set the data:
1 | In [214]: n = 1000 |
Now, to find prices per store/product, we can simply do:
1 | In [217]: (df.groupby(['Store', 'Product']) |
Piping can also be expressive when you want to deliver a grouped object to some
arbitrary function, for example:
1 | In [218]: def mean(groupby): |
where mean takes a GroupBy object and finds the mean of the Revenue and Quantity
columns respectively for each Store-Product combination. The mean function can
be any function that takes in a GroupBy object; the .pipe will pass the GroupBy
object as a parameter into the function you specify.
Examples
Regrouping by factor
Regroup columns of a DataFrame according to their sum, and sum the aggregated ones.
1 | In [220]: df = pd.DataFrame({'a': [1, 0, 0], 'b': [0, 1, 0], |
Multi-column factorization
By using ngroup(), we can extract
information about the groups in a way similar to factorize() (as described
further in the reshaping API) but which applies
naturally to multiple columns of mixed type and different
sources. This can be useful as an intermediate categorical-like step
in processing, when the relationships between the group rows are more
important than their content, or as input to an algorithm which only
accepts the integer encoding. (For more information about support in
pandas for full categorical data, see the Categorical
introduction and the
API documentation.)
1 | In [223]: dfg = pd.DataFrame({"A": [1, 1, 2, 3, 2], "B": list("aaaba")}) |
Groupby by indexer to ‘resample’ data
Resampling produces new hypothetical samples (resamples) from already existing observed data or from a model that generates data. These new samples are similar to the pre-existing samples.
In order to resample to work on indices that are non-datetimelike, the following procedure can be utilized.
In the following examples, df.index // 5 returns a binary array which is used to determine what gets selected for the groupby operation.
::: tip Note
The below example shows how we can downsample by consolidation of samples into fewer samples. Here by using df.index // 5, we are aggregating the samples in bins. By applying std() function, we aggregate the information contained in many samples into a small subset of values which is their standard deviation thereby reducing the number of samples.
:::
1 | In [227]: df = pd.DataFrame(np.random.randn(10, 2)) |
Returning a Series to propagate names
Group DataFrame columns, compute a set of metrics and return a named Series.
The Series name is used as the name for the column index. This is especially
useful in conjunction with reshaping operations such as stacking in which the
column index name will be used as the name of the inserted column:
1 | In [231]: df = pd.DataFrame({'a': [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], |




