1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
|
.. currentmodule:: pandas
.. _groupby:
.. ipython:: python
:suppress:
import numpy as np
np.random.seed(123456)
np.set_printoptions(precision=4, suppress=True)
import pandas as pd
pd.options.display.max_rows = 15
import matplotlib
matplotlib.style.use('ggplot')
import matplotlib.pyplot as plt
plt.close('all')
from collections import OrderedDict
*****************************
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
Of these, the split step is the most straightforward. In fact, in many
situations you may wish to split the data set into groups and do something with
those groups yourself. In the apply step, we might wish to one of the
following:
- **Aggregation**: computing a summary statistic (or statistics) about each
group. Some examples:
- Compute group sums or means
- Compute group sizes / counts
- **Transformation**: perform some group-specific computations and return a
like-indexed. Some examples:
- Standardizing data (zscore) within 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:
- Discarding data that belongs to groups with only a few members
- Filtering 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:
.. code-block:: sql
SELECT Column1, Column2, mean(Column3), sum(Column4)
FROM SomeTable
GROUP BY Column1, Column2
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 :ref:`cookbook<cookbook.grouping>` for some advanced strategies
.. _groupby.split:
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 do the following:
.. code-block:: ipython
# default is axis=0
>>> grouped = obj.groupby(key)
>>> grouped = obj.groupby(key, axis=1)
>>> grouped = obj.groupby([key1, key2])
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 a ``label -> group name`` mapping
- For DataFrame objects, a string indicating a column to be used to group. Of
course ``df.groupby('A')`` is just syntactic sugar for
``df.groupby(df['A'])``, but it makes life simpler
- A list of any of the above things
Collectively we refer to the grouping objects as the **keys**. For example,
consider the following DataFrame:
.. ipython:: python
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)})
df
We could naturally group by either the ``A`` or ``B`` columns or both:
.. ipython:: python
grouped = df.groupby('A')
grouped = df.groupby(['A', 'B'])
These will split the DataFrame on its index (rows). We could also split by the
columns:
.. ipython::
In [4]: def get_letter_type(letter):
...: if letter.lower() in 'aeiou':
...: return 'vowel'
...: else:
...: return 'consonant'
...:
In [5]: grouped = df.groupby(get_letter_type, axis=1)
Starting with 0.8, pandas Index objects now 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:
.. ipython:: python
lst = [1, 2, 3, 1, 2, 3]
s = pd.Series([1, 2, 3, 10, 20, 30], lst)
grouped = s.groupby(level=0)
grouped.first()
grouped.last()
grouped.sum()
Note that **no splitting occurs** until it's needed. Creating the GroupBy object
only verifies that you've passed a valid mapping.
.. 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:
GroupBy sorting
~~~~~~~~~~~~~~~~~~~~~~~~~
By default the group keys are sorted during the ``groupby`` operation. You may however pass ``sort=False`` for potential speedups:
.. ipython:: python
df2 = pd.DataFrame({'X' : ['B', 'B', 'A', 'A'], 'Y' : [1, 2, 3, 4]})
df2.groupby(['X']).sum()
df2.groupby(['X'], sort=False).sum()
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``:
.. ipython:: python
df3 = pd.DataFrame({'X' : ['A', 'B', 'A', 'B'], 'Y' : [1, 4, 3, 2]})
df3.groupby(['X']).get_group('A')
df3.groupby(['X']).get_group('B')
.. _groupby.attributes:
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:
.. ipython:: python
df.groupby('A').groups
df.groupby(get_letter_type, axis=1).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:
.. ipython:: python
grouped = df.groupby(['A', 'B'])
grouped.groups
len(grouped)
.. _groupby.tabcompletion:
``GroupBy`` will tab complete column names (and other attributes)
.. ipython:: python
:suppress:
n = 10
weight = np.random.normal(166, 20, size=n)
height = np.random.normal(60, 10, size=n)
time = pd.date_range('1/1/2000', periods=n)
gender = np.random.choice(['male', 'female'], size=n)
df = pd.DataFrame({'height': height, 'weight': weight,
'gender': gender}, index=time)
.. ipython:: python
df
gb = df.groupby('gender')
.. ipython::
@verbatim
In [1]: gb.<TAB>
gb.agg gb.boxplot gb.cummin gb.describe gb.filter gb.get_group gb.height gb.last gb.median gb.ngroups gb.plot gb.rank gb.std gb.transform
gb.aggregate gb.count gb.cumprod gb.dtype gb.first gb.groups gb.hist gb.max gb.min gb.nth gb.prod gb.resample gb.sum gb.var
gb.apply gb.cummax gb.cumsum gb.fillna gb.gender gb.head gb.indices gb.mean gb.name gb.ohlc gb.quantile gb.size gb.tail gb.weight
.. ipython:: python
:suppress:
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)})
.. _groupby.multiindex:
GroupBy with MultiIndex
~~~~~~~~~~~~~~~~~~~~~~~
With :ref:`hierarchically-indexed data <advanced.hierarchical>`, it's quite
natural to group by one of the levels of the hierarchy.
Let's create a Series with a two-level ``MultiIndex``.
.. ipython:: python
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])
s = pd.Series(np.random.randn(8), index=index)
s
We can then group by one of the levels in ``s``.
.. ipython:: python
grouped = s.groupby(level=0)
grouped.sum()
If the MultiIndex has names specified, these can be passed instead of the level
number:
.. ipython:: python
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:
.. ipython:: python
s.sum(level='second')
Also as of v0.6, grouping with multiple levels is supported.
.. ipython:: python
:suppress:
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['doo', 'doo', 'bee', 'bee', 'bop', 'bop', 'bop', 'bop'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second', 'third'])
s = pd.Series(np.random.randn(8), index=index)
.. ipython:: python
s
s.groupby(level=['first', 'second']).sum()
More on the ``sum`` function and aggregation later.
DataFrame column selection in GroupBy
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Once you have created the GroupBy object from a DataFrame, for example, 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:
.. ipython:: python
grouped = df.groupby(['A'])
grouped_C = grouped['C']
grouped_D = grouped['D']
This is mainly syntactic sugar for the alternative and much more verbose:
.. ipython:: python
df['C'].groupby(df['A'])
Additionally this method avoids recomputing the internal grouping information
derived from the passed key.
.. _groupby.iterating:
Iterating through groups
------------------------
With the GroupBy object in hand, iterating through the grouped data is very
natural and functions similarly to ``itertools.groupby``:
.. ipython::
In [4]: grouped = df.groupby('A')
In [5]: for name, group in grouped:
...: print(name)
...: print(group)
...:
In the case of grouping by multiple keys, the group name will be a tuple:
.. ipython::
In [5]: for name, group in df.groupby(['A', 'B']):
...: print(name)
...: print(group)
...:
It's standard Python-fu but remember you can unpack the tuple in the for loop
statement if you wish: ``for (k1, k2), group in grouped:``.
Selecting a group
-----------------
A single group can be selected using ``GroupBy.get_group()``:
.. ipython:: python
grouped.get_group('bar')
Or for an object grouped on multiple columns:
.. ipython:: python
df.groupby(['A', 'B']).get_group(('bar', 'one'))
.. _groupby.aggregate:
Aggregation
-----------
Once the GroupBy object has been created, several methods are available to
perform a computation on the grouped data.
An obvious one is aggregation via the ``aggregate`` or equivalently ``agg`` method:
.. ipython:: python
grouped = df.groupby('A')
grouped.aggregate(np.sum)
grouped = df.groupby(['A', 'B'])
grouped.aggregate(np.sum)
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
:ref:`MultiIndex <advanced.hierarchical>` by default, though this can be
changed by using the ``as_index`` option:
.. ipython:: python
grouped = df.groupby(['A', 'B'], as_index=False)
grouped.aggregate(np.sum)
df.groupby('A', as_index=False).sum()
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``:
.. ipython:: python
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.
.. ipython:: python
grouped.size()
.. ipython:: python
grouped.describe()
.. 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 ones that reduce the dimension of the returned objects,
for example: ``mean, sum, size, count, std, var, sem, describe, first, last, nth, min, max``. This is
what happens when you do for example ``DataFrame.sum()`` and get back a ``Series``.
``nth`` can act as a reducer *or* a filter, see :ref:`here <groupby.nth>`
.. _groupby.aggregate.multifunc:
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:
.. ipython:: python
grouped = df.groupby('A')
grouped['C'].agg([np.sum, np.mean, np.std])
If a dict is passed, the keys will be used to name the columns. Otherwise the
function's name (stored in the function object) will be used.
.. ipython:: python
grouped['D'].agg({'result1' : np.sum,
'result2' : np.mean})
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:
.. ipython:: python
grouped.agg([np.sum, np.mean, np.std])
Passing a dict of functions has different behavior by default, see the next
section.
Applying different functions to DataFrame columns
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
By passing a dict to ``aggregate`` you can apply a different aggregation to the
columns of a DataFrame:
.. ipython:: python
grouped.agg({'C' : np.sum,
'D' : lambda x: np.std(x, ddof=1)})
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 :ref:`dispatching
<groupby.dispatch>`:
.. ipython:: python
grouped.agg({'C' : 'sum', 'D' : 'std'})
.. note::
If you pass a dict to ``aggregate``, the ordering of the output colums is
non-deterministic. If you want to be sure the output columns will be in a specific
order, you can use an ``OrderedDict``. Compare the output of the following two commands:
.. ipython:: python
grouped.agg({'D': 'std', 'C': 'mean'})
grouped.agg(OrderedDict([('D', 'std'), ('C', 'mean')]))
.. _groupby.aggregate.cython:
Cython-optimized aggregation functions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some common aggregations, currently only ``sum``, ``mean``, ``std``, and ``sem``, have
optimized Cython implementations:
.. ipython:: python
df.groupby('A').sum()
df.groupby(['A', 'B']).mean()
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).
.. _groupby.transform:
Transformation
--------------
The ``transform`` method returns an object that is indexed the same (same size)
as the one being grouped. Thus, the passed transform function should return a
result that is the same size as the group chunk. For example, suppose we wished
to standardize the data within each group:
.. ipython:: python
index = pd.date_range('10/1/1999', periods=1100)
ts = pd.Series(np.random.normal(0.5, 2, 1100), index)
ts = ts.rolling(window=100,min_periods=100).mean().dropna()
ts.head()
ts.tail()
key = lambda x: x.year
zscore = lambda x: (x - x.mean()) / x.std()
transformed = ts.groupby(key).transform(zscore)
We would expect the result to now have mean 0 and standard deviation 1 within
each group, which we can easily check:
.. ipython:: python
# Original Data
grouped = ts.groupby(key)
grouped.mean()
grouped.std()
# Transformed Data
grouped_trans = transformed.groupby(key)
grouped_trans.mean()
grouped_trans.std()
We can also visually compare the original and transformed data sets.
.. ipython:: python
compare = pd.DataFrame({'Original': ts, 'Transformed': transformed})
@savefig groupby_transform_plot.png
compare.plot()
Another common data transform is to replace missing data with the group mean.
.. ipython:: python
:suppress:
cols = ['A', 'B', 'C']
values = np.random.randn(1000, 3)
values[np.random.randint(0, 1000, 100), 0] = np.nan
values[np.random.randint(0, 1000, 50), 1] = np.nan
values[np.random.randint(0, 1000, 200), 2] = np.nan
data_df = pd.DataFrame(values, columns=cols)
.. ipython:: python
data_df
countries = np.array(['US', 'UK', 'GR', 'JP'])
key = countries[np.random.randint(0, 4, 1000)]
grouped = data_df.groupby(key)
# Non-NA count in each group
grouped.count()
f = lambda x: x.fillna(x.mean())
transformed = grouped.transform(f)
We can verify that the group means have not changed in the transformed data
and that the transformed data contains no NAs.
.. ipython:: python
grouped_trans = transformed.groupby(key)
grouped.mean() # original group means
grouped_trans.mean() # transformation did not change group means
grouped.count() # original has some missing data points
grouped_trans.count() # counts after transformation
grouped_trans.size() # Verify non-NA count equals group size
.. note::
Some functions when applied to a groupby object will automatically transform the input, 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``.
.. ipython:: python
grouped.ffill()
.. _groupby.transform.window_resample:
New syntax to window and resample operations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 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()`` and
``rolling()`` 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.
.. ipython:: python
df_re = pd.DataFrame({'A': [1] * 10 + [5] * 10,
'B': np.arange(20)})
df_re
df_re.groupby('A').rolling(4).B.mean()
The ``expanding()`` method will accumulate a given operation
(``sum()`` in the example) for all the members of each particular
group.
.. ipython:: python
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.
.. ipython:: python
df_re = pd.DataFrame({'date': pd.date_range(start='2016-01-01',
periods=4,
freq='W'),
'group': [1, 1, 2, 2],
'val': [5, 6, 7, 8]}).set_index('date')
df_re
df_re.groupby('group').resample('1D').ffill()
.. _groupby.filter:
Filtration
----------
.. versionadded:: 0.12
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.
.. ipython:: python
sf = pd.Series([1, 1, 2, 3, 3, 3])
sf.groupby(sf).filter(lambda x: x.sum() > 2)
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.
.. ipython:: python
dff = pd.DataFrame({'A': np.arange(8), 'B': list('aabbbbcc')})
dff.groupby('B').filter(lambda x: len(x) > 2)
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.
.. ipython:: python
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.
.. ipython:: python
dff['C'] = np.arange(8)
dff.groupby('B').filter(lambda x: len(x['C']) > 2)
.. 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``.
.. ipython:: python
dff.groupby('B').head(2)
.. _groupby.dispatch:
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:
.. ipython:: python
grouped = df.groupby('A')
grouped.agg(lambda x: x.std())
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:
.. ipython:: python
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:
.. ipython:: python
tsdf = pd.DataFrame(np.random.randn(1000, 3),
index=pd.date_range('1/1/2000', periods=1000),
columns=['A', 'B', 'C'])
tsdf.ix[::2] = np.nan
grouped = tsdf.groupby(lambda x: x.year)
grouped.fillna(method='pad')
In this example, we chopped the collection of time series into yearly chunks
then independently called :ref:`fillna <missing_data.fillna>` on the
groups.
.. versionadded:: 0.14.1
The ``nlargest`` and ``nsmallest`` methods work on ``Series`` style groupbys:
.. ipython:: python
s = pd.Series([9, 8, 7, 5, 19, 1, 4.2, 3.3])
g = pd.Series(list('abababab'))
gb = s.groupby(g)
gb.nlargest(3)
gb.nsmallest(3)
.. _groupby.apply:
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:
.. ipython:: python
df
grouped = df.groupby('A')
# could also just call .describe()
grouped['C'].apply(lambda x: x.describe())
The dimension of the returned result can also change:
.. ipython::
In [8]: grouped = df.groupby('A')['C']
In [10]: def f(group):
....: return pd.DataFrame({'original' : group,
....: 'demeaned' : group - group.mean()})
....:
In [11]: grouped.apply(f)
``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
.. ipython:: python
def f(x):
return pd.Series([ x, x**2 ], index = ['x', 'x^2'])
s = pd.Series(np.random.rand(5))
s
s.apply(f)
.. 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.
.. warning::
In the current implementation apply calls func twice on the
first group to decide whether it can take a fast or slow code
path. This can lead to unexpected behavior if func has
side-effects, as they will take effect twice for the first
group.
.. ipython:: python
d = pd.DataFrame({"a":["x", "y"], "b":[1,2]})
def identity(df):
print df
return df
d.groupby("a").apply(identity)
Other useful features
---------------------
Automatic exclusion of "nuisance" columns
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Again consider the example DataFrame we've been looking at:
.. ipython:: python
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:
.. ipython:: python
df.groupby('A').std()
.. _groupby.missing:
NA and NaT group handling
~~~~~~~~~~~~~~~~~~~~~~~~~
If there are any NaN or NaT values in the grouping key, these will be automatically
excluded. So 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:
.. ipython:: python
data = pd.Series(np.random.randn(100))
factor = pd.qcut(data, [0, .25, .5, .75, 1.])
data.groupby(factor).mean()
.. _groupby.specify:
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.
.. ipython:: python
import datetime
df = pd.DataFrame({
'Branch' : 'A A A A A A A B'.split(),
'Buyer': 'Carl Mark Carl Carl Joe Joe Joe Carl'.split(),
'Quantity': [1,3,5,1,8,1,9,3],
'Date' : [
datetime.datetime(2013,1,1,13,0),
datetime.datetime(2013,1,1,13,5),
datetime.datetime(2013,10,1,20,0),
datetime.datetime(2013,10,2,10,0),
datetime.datetime(2013,10,1,20,0),
datetime.datetime(2013,10,2,10,0),
datetime.datetime(2013,12,2,12,0),
datetime.datetime(2013,12,2,14,0),
]
})
df
Groupby a specific column with the desired frequency. This is like resampling.
.. ipython:: python
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.
.. ipython:: python
df = df.set_index('Date')
df['Date'] = df.index + pd.offsets.MonthEnd(2)
df.groupby([pd.Grouper(freq='6M',key='Date'),'Buyer']).sum()
df.groupby([pd.Grouper(freq='6M',level='Date'),'Buyer']).sum()
Taking the first rows of each group
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Just like for a DataFrame or Series you can call head and tail on a groupby:
.. ipython:: python
df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])
df
g = df.groupby('A')
g.head(1)
g.tail(1)
This shows the first or last n rows from each group.
.. warning::
Before 0.14.0 this was implemented with a fall-through apply,
so the result would incorrectly respect the as_index flag:
.. code-block:: python
>>> g.head(1): # was equivalent to g.apply(lambda x: x.head(1))
A B
A
1 0 1 2
5 2 5 6
.. _groupby.nth:
Taking the nth row of each group
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To select from a DataFrame or Series the nth item, use the nth method. This is a reduction method, and will return a single row (or no row) per group if you pass an int for n:
.. ipython:: python
df = pd.DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])
g = df.groupby('A')
g.nth(0)
g.nth(-1)
g.nth(1)
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, for a Series this just needs to be truthy.
.. ipython:: python
# nth(0) is the same as g.first()
g.nth(0, dropna='any')
g.first()
# nth(-1) is the same as g.last()
g.nth(-1, dropna='any') # NaNs denote group exhausted when using dropna
g.last()
g.B.nth(0, dropna=True)
As with other methods, passing ``as_index=False``, will achieve a filtration, which returns the grouped row.
.. ipython:: python
df = pd.DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])
g = df.groupby('A',as_index=False)
g.nth(0)
g.nth(-1)
You can also select multiple rows from each group by specifying multiple nth values as a list of ints.
.. ipython:: python
business_dates = pd.date_range(start='4/1/2014', end='6/30/2014', freq='B')
df = pd.DataFrame(1, index=business_dates, columns=['a', 'b'])
# get the first, 4th, and last date index for each month
df.groupby((df.index.year, df.index.month)).nth([0, 3, -1])
Enumerate group items
~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 0.13.0
To see the order in which each row appears within its group, use the
``cumcount`` method:
.. ipython:: python
df = pd.DataFrame(list('aaabba'), columns=['A'])
df
df.groupby('A').cumcount()
df.groupby('A').cumcount(ascending=False) # kwarg only
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.
.. ipython:: python
np.random.seed(1234)
df = pd.DataFrame(np.random.randn(50, 2))
df['g'] = np.random.choice(['A', 'B'], size=50)
df.loc[df['g'] == 'B', 1] += 3
We can easily visualize this with a boxplot:
.. ipython:: python
:okwarning:
@savefig groupby_boxplot.png
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 :ref:`visualization documentation<visualization.box>` for more.
.. warning::
For historical reasons, ``df.groupby("g").boxplot()`` is not equivalent
to ``df.boxplot(by="g")``. See :ref:`here<visualization.box.return>` for
an explanation.
Examples
--------
Regrouping by factor
~~~~~~~~~~~~~~~~~~~~
Regroup columns of a DataFrame according to their sum, and sum the aggregated ones.
.. ipython:: python
df = pd.DataFrame({'a':[1,0,0], 'b':[0,1,0], 'c':[1,0,0], 'd':[2,3,4]})
df
df.groupby(df.sum(), axis=1).sum()
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 get's selected for the groupby operation.
.. 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.
.. ipython:: python
df = pd.DataFrame(np.random.randn(10,2))
df
df.index // 5
df.groupby(df.index // 5).std()
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:
.. ipython:: python
df = pd.DataFrame({
'a': [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2],
'b': [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],
'c': [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
'd': [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1],
})
def compute_metrics(x):
result = {'b_sum': x['b'].sum(), 'c_mean': x['c'].mean()}
return pd.Series(result, name='metrics')
result = df.groupby('a').apply(compute_metrics)
result
result.stack()
|