从索引到条件从 Pandas DataFrame 获取行

poo*_*kie 5 python indexing series python-3.x pandas

假设我有一个 Pandas DataFrame:

x = pd.DataFrame(data=[5,4,3,2,1,0,1,2,3,4,5],columns=['value'])
x
Out[9]: 
    value
0       5
1       4
2       3
3       2
4       1
5       0
6       1
7       2
8       3
9       4
10      5
Run Code Online (Sandbox Code Playgroud)

现在,我想,给定一个索引,在x满足条件之前查找行。例如,如果index = 2

x.loc[2]
Out[14]: 
value    3
Name: 2, dtype: int64
Run Code Online (Sandbox Code Playgroud)

现在我想从中index找到n值大于 some的下一行threshold。例如,如果threshold is 0,结果应该是:

x
Out[9]: 
    value
2       3
3       2
4       1
5       0
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

我试过了:

x.loc[2:x['value']>0,:]
Run Code Online (Sandbox Code Playgroud)

但当然这不会起作用,因为x['value']>0返回一个布尔数组:

Out[20]: 
0      True
1      True
2      True
3      True
4      True
5     False
6      True
7      True
8      True
9      True
10     True
Name: value, dtype: bool
Run Code Online (Sandbox Code Playgroud)

raf*_*elc 5

使用idxmin和切片

x.loc[2:x['value'].gt(0).idxmin(),:]

2    3
3    2
4    1
5    0
Name: value
Run Code Online (Sandbox Code Playgroud)

编辑:

对于通用公式,请使用

index = 7
threshold = 2
x.loc[index:x.loc[index:,'value'].gt(threshold).idxmin(),:]
Run Code Online (Sandbox Code Playgroud)

从您在评论中的描述来看,您似乎想从而index+1不是索引开始。所以,如果是这种情况,只需使用

x.loc[index+1:x.loc[index+1:,'value'].gt(threshold).idxmin(),:]
Run Code Online (Sandbox Code Playgroud)