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
+54
Original file line number
Diff line number
Diff line change
@@ -799,6 +799,60 @@ no column selection, so the values are just the functions.
799
799
max_height="max",
800
800
)
801
801
802
+
803
+
Passing a List of Tuples
804
+
~~~~~~~~~~~~~~~~~~~~~~~~~
805
+
806
+
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:
822
+
823
+
.. ipython:: python
824
+
825
+
result = df.groupby('key')['data'].agg([('foo', 'mean')])
826
+
827
+
In this example, the output column 'foo' contains the mean value of the 'data' column for each group.
828
+
829
+
To apply multiple aggregations to the same column, you can pass a list of tuples:
830
+
831
+
.. ipython:: python
832
+
833
+
result = df.groupby('key')['data'].agg([('col1', 'mean'), ('col2', 'std')])
834
+
835
+
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.
836
+
837
+
Similarly, you can extend this approach to include more aggregations:
838
+
839
+
.. ipython:: python
840
+
841
+
result = df.groupby('key')['data'].agg([('col1', 'mean'), ('col2', 'std'), ('col3', 'min')])
842
+
843
+
Here, the resulting DataFrame will have three columns: 'col1', 'col2', and 'col3', each containing the respective aggregation result for the 'data' column.
844
+
845
+
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:
846
+
847
+
.. ipython:: python
848
+
849
+
result = df.groupby('key')['data'].agg([('mean_value', 'mean'), ('median_value', 'median')])
850
+
851
+
The resulting DataFrame will have two columns: 'mean_value' and 'median_value', each containing the corresponding aggregation results.
852
+
853
+
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.
0 commit comments