我想对列中的值使用 iloc。
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']})
我想在每个列值中选择索引 2 作为数据框,结果如下
col1 col2
1 C
2 F
3 K
非常感谢
最佳答案
使用GroupBy.nth
:
df2 = df1.groupby('col1', as_index=False).nth(2)
替代 GroupBy.cumcount
:
df2 = df1[df1.groupby('col1').cumcount().eq(2)]
print (df2)
col1 col2
2 1 C
5 2 F
10 3 K
关于python - iloc[] 按值列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71392956/