熊猫数据框-在匹配行之前/之后获取第N行

时间:2020-11-12 20:47:29

标签: python pandas dataframe search match

如何获取匹配行之前/之后的第N行?

df_temp[df_temp.Date == pd.to_datetime(specific_date)] 

1 个答案:

答案 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是否在范围之内。

我们可以通过比较0len(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)}")