如何获取匹配行之前/之后的第N行?
df_temp[df_temp.Date == pd.to_datetime(specific_date)]
答案 0 :(得分:1)
您可以通过以下方式获取匹配的第一行的索引
idx = df_temp[df_temp.Date == pd.to_datetime(specific_date)].index[0]
然后您可以使用
获取(idx-n
之前或(idx+n
)之后的第n行。
df_temp.iloc[idx+n]
根据@Ruli的评论进行编辑:
如果我们想将其构建为强大的解决方案,我们当然必须检查新索引idx+n
是否在范围之内。
我们可以通过比较0
和len(df_temp)
来做到这一点。
new_idx = idx + n
if new_idx >= 0 and new_idx <= len(df_temp)-1:
df_temp.iloc[new_idx]
else:
print(f"Index {new_idx} is out of bounds for DataFrame of size {len(df_temp)}")