gpt4 book ai didi

python - iloc[] 按值列

转载 作者:行者123 更新时间:2023-12-05 09:28:21 24 4
gpt4 key购买 nike

我想对列中的值使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com