iloc[] by value columns

Question:

I want to use iloc with value in column.

df1 = pd.DataFrame({'col1': ['1' ,'1','1','2','2','2','2','2','3' ,'3','3'],
                'col2': ['A' ,'B','C','D','E','F','G','H','I' ,'J','K']})

I want to select index 2 in each column value as data frame and the result will be like

col1 col2
   1    C
   2    F
   3    K

Thank you so much

Asked By: Putthita Nuphasant

||

Answers:

Use GroupBy.nth with as_index=False:

df1.groupby('col1', as_index=False).nth(2)

output:

   col1 col2
2     1    C
5     2    F
10    3    K
Answered By: mozway

Use GroupBy.nth:

df2 = df1.groupby('col1', as_index=False).nth(2)

Alternative with GroupBy.cumcount:

df2 = df1[df1.groupby('col1').cumcount().eq(2)]

print (df2)
   col1 col2
2     1    C
5     2    F
10    3    K
Answered By: jezrael
df1.groupby('col1').agg(lambda ss:ss.iloc[2])

   col2
col1     
1       C
2       F
3       K
Answered By: G.G
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.