Reset index of grouped data frames

Question:

I would like to reset the index of grouped data frames and based on the examples, I have written:

for name, df_group in df.groupby('BL', as_index=False):
    print(df_group)

But the output shows that index has not been reset.

      Num               BL  Home  Requester
4   16986  140080043863936     5          5
5   16987  140080043863936     0          5
10  16986  140080043863936     7          5

How can I fix that?

Asked By: mahmood

||

Answers:

The as_index=False option of groupby is useful for groupby methods (it prevents the grouper to become the new index and keeps it as a column), not when looping over the groups manually.

You have to reset_index here:

for name, df_group in df.groupby('BL'):
    print(df_group.reset_index(drop=True))
Answered By: mozway

as_index=False does not mean to give 0, 1, … N index result at the end; it means not to put the grouper(s) to the index but in columns, i.e., "BL" in your case. You can explicitly reset index in the loop:

for name, df_group in df.groupby("BL"):
    print(df_group.reset_index(drop=True))
Answered By: Mustafa Aydın

I would try:

print(df_group.reset_index(drop=True))
Answered By: Simone Castellano
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.