Home > Net >  iloc[] by value columns
iloc[] by value columns

Time:03-08

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

CodePudding user response:

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

CodePudding user response:

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
  • Related