pandas 选择符合我的条件的特定行之前和之后的特定行

Ant*_*ny 7 python indexing pandas

我有一个数据框。第一行中的任何位置都有一个满足我的标准的独特值。例如 t = 800

现在我想找到该值所在的行,并从之前的 n 行到之后的 n 行中进行选择。

我试过:

idx = df[df['t']==stime]
from_idx = idx-1200
to_idx = idx + 1200
vib = df.iloc[to_idx:from_idx]
Run Code Online (Sandbox Code Playgroud)

它找到符合我的标准的行,但我无法从我的数据框中获得正确的选择

jpp*_*jpp 8

idx在你的逻辑中是一个pd.DataFrame对象,而不是代表行索引的标量。如果您提取标量索引,假设您的索引是唯一的,您可以使用它pd.Index.get_loc来获取整数位置:

idx = df.index.get_loc(df[df['t'] == stime].index[0])
vib = df.iloc[idx - 1200: idx + 1200]
Run Code Online (Sandbox Code Playgroud)