我有一个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的值进行排序。
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谢谢
发布于 2015-07-17 19:22:45
你可以:
df.groupby('months_to_maturity').head(3)https://stackoverflow.com/questions/31482826
复制相似问题