Pandas core groupby DataFrameGroupBy function ngroup() in Python
The Pandas core groupby DataFrameGroupBy function ngroup() used to retrieve the number that represents the each group from 0 to the number of group - 1. It returns a Series that represents the unique numbers for each group.
Syntax
 1 DataFrameGroupBy.ngroup(ascending = True)
ascending : It is a boolean value that specifies whether to sort the result in ascending. If not specified, the default value will be True.
1. False : If specified, it reverse the group number from group - 1 to 0.2. True : It is default, if not specified, that order group number from 0 to group - 1.
ngroup() function
 1 import pandas as pd
 2 import numpy as np
 3 
 4 df = pd.DataFrame({'A' : ['A1', 'A2', 'A2', 'A1', 'A3', 'A2', 'A3'],
 5 			'B' : [1, np.nan, 6, 3, 5, np.nan, 8],
 6 			'C' : [3, 6, np.nan, 3, 5, -3, np.nan]})
 7 
 8 grouped = df.groupby('A')
 9 res = grouped.ngroup()
 10 
 11 print('The ascending on group number :')
 12 print(res)
In the above example, a DataFrame object is created by passing a dictionary. A DataFrameGroupBy function ngroup() is called that assign group number to each elements. The result is assign to the variable that will be printed on console.
Output
 1 The ascending on group number :
 2 0    0 # A1 as 0
 3 1    1 # A2 as 1
 4 2    1 # A2 as 1
 5 3    0 # A1 as 0
 6 4    2 # A3 as 2
 7 5    1 # A2 as 1
 8 6    2 # A3 as 2
 9 dtype: int64

ngroup() with Series

ngroup() with Series
 1 import pandas as pd
 2 import numpy as np
 3 
 4 idx = ['A1', 'A2', 'A2', 'A1', 'A3', 'A2', 'A3']
 5 ser = pd.Series([3, 6, np.nan, 3, 5, 3, np.nan], index = idx)
 6 
 7 grouped = ser.groupby(ser.index)
 8 # or 
 9 # grouped = ser.groupby(level = 0)
 10 res = grouped.ngroup()
 11 
 12 print('The ascending on group number :')
 13 print(res)
In the above example, a Series object is created by passing an array and index. A SeriesGroupBy function ngroup() is called that assign group number to each elements.
Output
 1 The ascending on group number :
 2 A1    0
 3 A2    1
 4 A2    1
 5 A1    0
 6 A3    2
 7 A2    1
 8 A3    2
 9 dtype: int64
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us