How to use as_index() function In Python Pandas

Pandas provide a function called as_index() which is specified by a boolean value. The as_index() functions groups the dataframe by the specified aggregate function and if  as_index() value is False, the resulting dataframe is flattened.

Syntax: pandas.DataFrame.groupby(by, level, axis, as_index)

Parameters:

  • by – specifies the columns on which the groupby operation has to be performed
  • level – specifies the index at which the columns has to be grouped
  • axis – specifies whether to split along rows (0) or columns (1)
  • as_index – Returns an object with group labels as the index, for aggregated output.

Example:

In this example,  We are using the pandas groupby function to group car sales data by quarters and mention the as_index parameter as False and specify the as_index parameter as false ensures that the hierarchical index of the grouped dataframe is flattened.

Python3




# group by cars based on the
# sum of sales on quarter 1 and 2
# and mention as_index is False
grouped_data = data.groupby(by="cars", as_index=False).agg("sum")
 
# display
print(grouped_data)


Output:

How to flatten a hierarchical index in Pandas

How to flatten a hierarchical index in Pandas DataFrame columns?

In this article, we are going to see the flatten a hierarchical index in Pandas DataFrame columns. Hierarchical Index usually occurs as a result of groupby() aggregation functions. Flatten hierarchical index in Pandas, the aggregated function used will appear in the hierarchical index of the resulting dataframe.

Similar Reads

Using reset_index() function

Pandas provide a function called reset_index() to flatten the hierarchical index created due to the groupby aggregation function in Python....

Using as_index() function

...

Flattening hierarchical index in pandas dataframe using groupby

Pandas provide a function called as_index() which is specified by a boolean value. The as_index() functions groups the dataframe by the specified aggregate function and if  as_index() value is False, the resulting dataframe is flattened....

Flattening hierarchical index using to_records() function

...

Flattening hierarchical columns using join() and rstrip()

Whenever we use the groupby function on a single column with multiple aggregation functions we get multiple hierarchical indexes based on the aggregation type. In such cases, the hierarchical index has to be flattened at both levels....