What is as_index in groupby in pandas? & Difference between “as_index = False” and “reset_index()”

Take a look:

import pandas as pd

df = pd.DataFrame(data={'books':['bk1','bk1','bk1','bk2','bk2','bk3'], 'price': [12,12,12,15,15,17]})

print(df)

print(df.groupby('books', as_index=True).sum())

print(df.groupby('books', as_index=False).sum())

Output:

  books  price
0   bk1     12
1   bk1     12
2   bk1     12
3   bk2     15
4   bk2     15
5   bk3     17

       price
books       
bk1       36
bk2       30
bk3       17

  books  price
0   bk1     36
1   bk2     30
2   bk3     17

When as_index=True the key(s) you use in groupby() will become an index in the new dataframe.

The benefits you get when you set the column as index are:

  1. Speed. When you filter values based on the index column eg. df.loc['bk1'], it would be faster because of hashing of index column. It doesn't have to traverse the entire books column to find 'bk1'. It will just calculate the hash value of 'bk1' and find it in 1 go.

  2. Ease. When as_index=True you can use this syntax df.loc['bk1'] which is shorter and faster as opposed to df.loc[df.books=='bk1'] which is longer and slower.

In addition,

 

11

 

1

 

I just wanted to know what is the difference in the function performed by these 2.

Data:

import pandas as pd
df = pd.DataFrame({"ID":["A","B","A","C","A","A","C","B"], "value":[1,2,4,3,6,7,3,4]})

as_index=False :

df_group1 = df.groupby("ID").sum().reset_index()

reset_index() :

df_group2 = df.groupby("ID", as_index=False).sum()

Both of them give the exact same output.

  ID  value
0  A     18
1  B      6
2  C      6

Can anyone tell me what is the difference and any example illustrating the same?

 

No, they're only the same in this particular case because the OP's dataframe doesn't have an explicit index other than the default one 0,1,2... so keeping it or resetting/dropping it doesn't make a difference. If the dataframe actually had an index e.g. 100, 101, 102.. the results would not be the same. – smci Sep 23 '19 at 17:09 

Guess you like

Origin blog.csdn.net/weixin_51267929/article/details/114242425