g1 here is a DataFrame. It has a hierarchical index, though:

In [19]: type(g1)
Out[19]: pandas.core.frame.DataFrame

In [20]: g1.index
Out[20]: 
MultiIndex([('Alice', 'Seattle'), ('Bob', 'Seattle'), ('Mallory', 'Portland'),
       ('Mallory', 'Seattle')], dtype=object)

Perhaps you want something like this?

In [21]: g1.add_suffix('_Count').reset_index()
Out[21]: 
      Name      City  City_Count  Name_Count
0    Alice   Seattle           1           1
1      Bob   Seattle           2           2
2  Mallory  Portland           2           2
3  Mallory   Seattle           1           1

Or something like:

In [36]: DataFrame({'count' : df1.groupby( [ "Name", "City"] ).size()}).reset_index()
Out[36]: 
      Name      City  count
0    Alice   Seattle      1
1      Bob   Seattle      2
2  Mallory  Portland      2
3  Mallory   Seattle      1
Answer from Wes McKinney on Stack Overflow
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.Series.groupby.html
pandas.Series.groupby — pandas 3.0.2 documentation
A label or list of labels may be passed to group by the columns in self. Notice that a tuple is interpreted as a (single) key. levelint, level name, or sequence of such, default None · If the axis is a MultiIndex (hierarchical), group by a particular level or levels. Do not specify both by and level. ... Return object with group labels as the index. Only relevant for DataFrame ...
Top answer
1 of 13
709

g1 here is a DataFrame. It has a hierarchical index, though:

In [19]: type(g1)
Out[19]: pandas.core.frame.DataFrame

In [20]: g1.index
Out[20]: 
MultiIndex([('Alice', 'Seattle'), ('Bob', 'Seattle'), ('Mallory', 'Portland'),
       ('Mallory', 'Seattle')], dtype=object)

Perhaps you want something like this?

In [21]: g1.add_suffix('_Count').reset_index()
Out[21]: 
      Name      City  City_Count  Name_Count
0    Alice   Seattle           1           1
1      Bob   Seattle           2           2
2  Mallory  Portland           2           2
3  Mallory   Seattle           1           1

Or something like:

In [36]: DataFrame({'count' : df1.groupby( [ "Name", "City"] ).size()}).reset_index()
Out[36]: 
      Name      City  count
0    Alice   Seattle      1
1      Bob   Seattle      2
2  Mallory  Portland      2
3  Mallory   Seattle      1
2 of 13
193

I want to slightly change the answer given by Wes, because version 0.16.2 requires as_index=False. If you don't set it, you get an empty dataframe.

Source:

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 here.

import pandas as pd

df1 = pd.DataFrame({"Name":["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"],
                    "City":["Seattle","Seattle","Portland","Seattle","Seattle","Portland"]})
print df1
#
#       City     Name
#0   Seattle    Alice
#1   Seattle      Bob
#2  Portland  Mallory
#3   Seattle  Mallory
#4   Seattle      Bob
#5  Portland  Mallory
#
g1 = df1.groupby(["Name", "City"], as_index=False).count()
print g1
#
#                  City  Name
#Name    City
#Alice   Seattle      1     1
#Bob     Seattle      2     2
#Mallory Portland     2     2
#        Seattle      1     1
#

EDIT:

In version 0.17.1 and later you can use subset in count and reset_index with parameter name in size:

print df1.groupby(["Name", "City"], as_index=False ).count()
#IndexError: list index out of range

print df1.groupby(["Name", "City"]).count()
#Empty DataFrame
#Columns: []
#Index: [(Alice, Seattle), (Bob, Seattle), (Mallory, Portland), (Mallory, Seattle)]

print df1.groupby(["Name", "City"])[['Name','City']].count()
#                  Name  City
#Name    City                
#Alice   Seattle      1     1
#Bob     Seattle      2     2
#Mallory Portland     2     2
#        Seattle      1     1

print df1.groupby(["Name", "City"]).size().reset_index(name='count')
#      Name      City  count
#0    Alice   Seattle      1
#1      Bob   Seattle      2
#2  Mallory  Portland      2
#3  Mallory   Seattle      1

The difference between count and size is that size counts NaN values while count does not.

🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › convert groupby output from series to dataframe?
Convert GroupBy output from Series to DataFrame? - Spark By {Examples}
December 11, 2024 - How to Convert a GroupBy output from Series to Pandas DataFrame? Performing aggregation function after groupby() function returns a pandas Series hence
🌐
Pandas
pandas.pydata.org › pandas-docs › stable › reference › api › pandas.Series.groupby.html
pandas.Series.groupby — pandas 3.0.1 documentation
A label or list of labels may be passed to group by the columns in self. Notice that a tuple is interpreted as a (single) key. levelint, level name, or sequence of such, default None · If the axis is a MultiIndex (hierarchical), group by a particular level or levels. Do not specify both by and level. ... Return object with group labels as the index. Only relevant for DataFrame ...
🌐
Pandas
pandas.pydata.org › docs › reference › groupby.html
GroupBy — pandas 3.0.2 documentation - PyData |
Back to top · Search Ctrl+K · Choose version · GitHub · X · Mastodon · Search Ctrl+K · Choose version · GitHub · X · Mastodon · pandas.api.typing.DataFrameGroupBy and pandas.api.typing.SeriesGroupBy instances are returned by groupby calls pandas.DataFrame.groupby() and pandas.Series.groupby() respectively.
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 0.25.3 › reference › api › pandas.Series.groupby.html
pandas.Series.groupby — pandas 0.25.3 documentation
>>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'], ... ['Captive', 'Wild', 'Captive', 'Wild']] >>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type')) >>> df = pd.DataFrame({'Max Speed': [390., 350., 30., 20.]}, ...
🌐
Pandas
pandas.pydata.org › docs › dev › reference › api › pandas.core.groupby.SeriesGroupBy.transform.html
pandas.core.groupby.SeriesGroupBy.transform — pandas 3.0.0.dev0+2098.g9c5b9ee823 documentation
The group data and group index ... arrays to the JITed user defined function, and no alternative execution attempts will be tried. Changed in version 1.3.0: The resulting dtype will reflect the return value of the passed func, see the examples below. Changed in version 2.0.0: When using .transform on a grouped DataFrame and the transformation function returns a DataFrame, pandas now aligns ...
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › python-pandas-dataframe-groupby
Pandas dataframe.groupby() Method - GeeksforGeeks
You can apply various functions to each group, such as: Aggregation: Calculate summary statistics (e.g., sum, mean, count) for each group. Transformation: Modify the values within each group. Filtering: Keep or discard groups based on certain conditions. Combining: Finally, the results of the applied function are combined into a new DataFrame or Series.
Published   July 11, 2025
🌐
pandas
pandas.pydata.org › pandas-docs › dev › reference › api › pandas.Series.groupby.html
pandas.Series.groupby — pandas ain documentation
A label or list of labels may be passed to group by the columns in self. Notice that a tuple is interpreted as a (single) key. levelint, level name, or sequence of such, default None · If the axis is a MultiIndex (hierarchical), group by a particular level or levels. Do not specify both by and level. ... Return object with group labels as the index. Only relevant for DataFrame ...
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.groupby.html
pandas.DataFrame.groupby — pandas 3.0.2 documentation
Group DataFrame using a mapper or by a Series of columns. A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups.
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 0.21 › generated › pandas.Series.groupby.html
pandas.Series.groupby — pandas 0.21.1 documentation
Group series using mapper (dict or key function, apply given function to group, return result as series) or by a series of columns. Examples · DataFrame results · >>> data.groupby(func, axis=0).mean() >>> data.groupby(['col1', 'col2'])['col3'].mean() DataFrame with hierarchical index · >>> ...
🌐
Statology
statology.org › home › how to convert pandas groupby output to dataframe
How to Convert Pandas GroupBy Output to DataFrame
March 31, 2022 - import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'], 'position': ['G', 'G', 'F', 'C', 'G', 'F', 'F', 'F'], 'points': [5, 7, 7, 10, 12, 22, 15, 10]}) #view DataFrame print(df) team position points 0 A G 5 1 A G 7 2 A F 7 3 A C 10 4 B G 12 5 B F 22 6 B F 15 7 B F 10
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.core.groupby.SeriesGroupBy.get_group.html
pandas.core.groupby.SeriesGroupBy.get_group — pandas 2.3.1 documentation
Back to top · GitHub · Twitter · Mastodon · SeriesGroupBy.get_group(name, obj=None)[source]# Construct DataFrame from group with provided name. Parameters: nameobject · The name of the group to get as a DataFrame. objDataFrame, default None · The DataFrame to take the DataFrame out of.
🌐
w3resource
w3resource.com › pandas › series › series-groupby.php
Pandas: Series - groupby() function - w3resource
This can be used to group large amounts of data and compute operations on these groups ... Series.groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False, **kwargs) ... Returns: DataFrameGroupBy or SeriesGroupBy Depends on the calling object and returns groupby object that contains information about the groups. ... import numpy as np import pandas as pd df = pd.DataFrame({'Animal': ['Tiger', 'Tiger', 'Dog', 'Dog'], 'Max Speed': [270., 260., 36., 32.]}) df
🌐
Apache
spark.apache.org › docs › latest › api › python › reference › pyspark.pandas › api › pyspark.pandas.Series.groupby.html
pyspark.pandas.Series.groupby — PySpark 4.1.1 documentation
If True, and if group keys contain NA values, NA values together with row/column will be dropped. If False, NA values will also be treated as the key in groups. ... Depends on the calling object and returns groupby object that contains information about the groups. ... >>> df = ps.DataFrame({'Animal': ['Falcon', 'Falcon', ...
🌐
TutorialsPoint
tutorialspoint.com › python_pandas › python_pandas_groupby.htm
Python Pandas - GroupBy
Let us now see how the grouping objects can be applied to the Pandas DataFrame using the groupby() method.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.core.groupby.DataFrameGroupBy.transform.html
pandas.core.groupby.DataFrameGroupBy.transform — pandas 2.3.3 documentation
The group data and group index ... arrays to the JITed user defined function, and no alternative execution attempts will be tried. Changed in version 1.3.0: The resulting dtype will reflect the return value of the passed func, see the examples below. Changed in version 2.0.0: When using .transform on a grouped DataFrame and the transformation function returns a DataFrame, pandas now aligns ...