Pandas: reset_index() after groupby.value_counts()

Given a pandas dataframe, we have to group by a column and computed value counts on another column. By Pranit Sharma Last updated : October 06, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose we are given the dataframe with some columns, we need to apply groupby() method on this dataframe and count the values of another column after using the reset_index() method. On using the reset_index() method on the grouped object we may get a ValueError.

reset_index() after groupby.value_counts()

To remove this ValueError we need to use the parameter name in the reset index method because the series name is the same as the name of one of the levels of multiindex. Also, we will apply the size() method here as it could be the best alternative for value_count.

Let's understand with the help of an example,

Python program for reset_index() after groupby.value_counts()

# Importing pandas
import pandas as pd

# Import numpy
import numpy as np

# Creating a dataframe
df = pd.DataFrame({

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Grouping the df
res = df.groupby(['a','b']).size().reset_index(name='count')

# Display result


The output of the above program is:

Example: Pandas: reset_index() after groupby.value_counts()frame

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.