标签:index False df 索引 books bk1 bk2 True
grouby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)
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
print df.groupby('books', as_index=True).sum()
print
print df.groupby('books', as_index=False).sum()
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 benefit of as_index=True is that you can yank out the rows you want by using key names. For eg. if you want ‘bk1’ you can get it like this: df.loc[‘bk1’] as opposed to when as_index=Falsethen you will have to get it like this: df.loc[df.books==‘bk1’]
Including the other main benefit of using as_index=True raised by @ayhan in comments: df.loc[‘bk1’] would be faster because it doesn’t have to traverse the entire books column to find ‘bk1’ when it’s indexed. It will just calculate the hash value of ‘bk1’ and find it in 1 go.
标签:index,False,df,索引,books,bk1,bk2,True 来源: https://blog.csdn.net/weixin_45271076/article/details/100180295
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。