首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在dataframe列中为特定值保留3行

在dataframe列中为特定值保留3行
EN

Stack Overflow用户
提问于 2015-07-17 18:55:57
回答 1查看 28关注 0票数 1

我有一个dataframe df,它有列months_to_maturity,并且有多个与months_to_maturity 1,2相关联的行,等等。我试图只保留与特定months_to_maturity值关联的前3行。例如,对于months_to_maturity = 1,我希望只有3行相关联的行,而对于months_to_maturity = 2,另外的3行等等。我尝试使用下面的代码来完成这个任务,但是得到了错误IndexError: index 21836 is out of bounds for axis 0 with size 4412,因此我想知道是否有更好的方法来做到这一点。pairwise给出了当前和下一行的数据。对months_to_maturity的值进行排序。

代码语言:javascript
复制
count = 0
for (i1, row1), (i2,row2) in pairwise(df.iterrows()):
    if row1.months_to_maturity == row2.months_to_maturity:
        count = count + 1
        if count == 3:
            df.drop(df.index[i1])
            df = df.reset_index()        
    elif row1.months_to_maturity != row2.months_to_maturity:
        count = 0

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-17 19:22:45

你可以:

代码语言:javascript
复制
df.groupby('months_to_maturity').head(3)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31482826

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档