Home > Mobile >  Reset index of grouped data frames
Reset index of grouped data frames

Time:01-12

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?

CodePudding user response:

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))

CodePudding user response:

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))

CodePudding user response:

I would try: print(df_group.reset_index(drop=True)

  • Related