1 DataFrameGroupBy.nth()
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.nth(1)
10
11 print('The 1st row from each group :')
12 print(res)
1 The 1st row from each group :
2 A B C
3 2 A2 6.0 NaN
4 3 A1 3.0 3.0
5 6 A3 8.0 NaN
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 # groups - 1 row
10 res = grouped.nth(-1)
11
12 print('The resulting rows from each group :')
13 print(res)
1 The resulting rows from each group :
2 A B C
3 3 A1 3.0 3.0
4 5 A2 NaN -3.0
5 6 A3 8.0 NaN
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.nth(slice(None, -1))
10
11 print('The resulting rows from each group :')
12 print(res)
1 The resulting rows from each group :
2 A B C
3 0 A1 1.0 3.0
4 1 A2 NaN 6.0
5 2 A2 6.0 NaN
6 4 A3 5.0 5.0
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, 2], index = idx)
6
7 grouped = ser.groupby(ser.index)
8 # or
9 # grouped = ser.groupby(level = 0)
10 res = grouped.nth(1)
11
12 print('The 1st row from each group :')
13 print(res)
1 The 1st row from each group :
2 A2 NaN
3 A1 3.0
4 A3 2.0
5 dtype: float64