How to count number of rows per group in pandas group by?
Count number of rows per group:
import pandas as pd df = pd.DataFrame([[10, 20, 30, 40], [7, 14, 21, 28], [5, 5, 0, 0], [6, 6, 6, 6], [8, 8, 8, 8], [5, 5, 0, 0]], columns=['Apple', 'Orange', 'Rice', 'Oil'], index=['Basket1', 'Basket2', 'Basket3', 'Basket4', 'Basket5', 'Basket6']) print(df) print("\n ----------------------------- \n") print(df[['Apple', 'Orange', 'Rice', 'Oil']]. groupby(['Apple']).agg(['mean', 'count']))
C:\pandas>pep8 example49.py C:\pandas>python example49.py Apple Orange Rice Oil Basket1 10 20 30 40 Basket2 7 14 21 28 Basket3 5 5 0 0 Basket4 6 6 6 6 Basket5 8 8 8 8 Basket6 5 5 0 0 ----------------------------- Orange Rice Oil mean count mean count mean count Apple 5 5 2 0 2 0 2 6 6 1 6 1 6 1 7 14 1 21 1 28 1 8 8 1 8 1 8 1 10 20 1 30 1 40 1 C:\pandas>
2018-10-28T10:13:36+05:30
2018-10-28T10:13:36+05:30
Amit Arora
Amit Arora
Python Programming Tutorial
Python
Practical Solution