Rtypuss
Rtypuss

Reputation: 47

iloc[] by value columns

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

Upvotes: 2

Views: 217

Answers (3)

G.G
G.G

Reputation: 765

df1.groupby('col1').agg(lambda ss:ss.iloc[2])

   col2
col1     
1       C
2       F
3       K

Upvotes: 0

jezrael
jezrael

Reputation: 863511

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

Upvotes: 4

mozway
mozway

Reputation: 262284

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

Upvotes: 3

Related Questions