You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: doc/source/user_guide/groupby.rst
-70Lines changed: 0 additions & 70 deletions
Original file line number
Diff line number
Diff line change
@@ -770,76 +770,6 @@ no column selection, so the values are just the functions.
770
770
max_height="max",
771
771
)
772
772
773
-
Passing a List of Tuples
774
-
~~~~~~~~~~~~~~~~~~~~~~~~~
775
-
776
-
Instead of a dictionary, you can also pass a list of tuples to the `agg` method to achieve similar results. Each tuple contains the output column name as the first element and the aggregation function as the second element. This approach is particularly useful for applying multiple aggregations on the same column.
Suppose we want to group the DataFrame by the 'key' column and apply different aggregations to the 'data' column:
792
-
793
-
.. ipython:: python
794
-
795
-
result = df.groupby('key')['data'].agg([('foo', 'mean')])
796
-
797
-
In this example, the output column 'foo' contains the mean value of the 'data' column for each group.
798
-
799
-
To apply multiple aggregations to the same column, you can pass a list of tuples:
800
-
801
-
.. ipython:: python
802
-
803
-
result = df.groupby('key')['data'].agg([('col1', 'mean'), ('col2', 'std')])
804
-
805
-
In this case, the resulting DataFrame will have two columns: 'col1' containing the mean and 'col2' containing the standard deviation of the 'data' column for each group.
806
-
807
-
Similarly, you can extend this approach to include more aggregations:
808
-
809
-
.. ipython:: python
810
-
811
-
result = df.groupby('key')['data'].agg([('col1', 'mean'), ('col2', 'std'), ('col3', 'min')])
812
-
813
-
Here, the resulting DataFrame will have three columns: 'col1', 'col2', and 'col3', each containing the respective aggregation result for the 'data' column.
814
-
815
-
In addition to the examples above, let's consider a scenario where we want to calculate both the mean and the median of the 'data' column for each group:
816
-
817
-
.. ipython:: python
818
-
819
-
result = df.groupby('key')['data'].agg([('mean_value', 'mean'), ('median_value', 'median')])
820
-
821
-
The resulting DataFrame will have two columns: 'mean_value' and 'median_value', each containing the corresponding aggregation results.
822
-
823
-
Using a list of tuples provides a concise way to apply multiple aggregations to the same column while controlling the output column names. This approach is especially handy when you need to calculate various statistics on the same data within each group.
824
-
825
-
For a copy-pastable example, consider the following DataFrame `df`:
0 commit comments