数据帧的Python筛选值

数据帧的Python筛选值,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有一个数据集,一旦超过某个值,我就需要对其进行筛选,但不能在之后进行筛选。以下是数据帧的一个示例: Dip MD 0 70 5000 1 80 6000 2 90 7000 3 80 8000 我想在Dip第一次超过85之前过滤掉所有内容,因此生成的数组应该如下所示: Dip MD 0 90 7000 1 80 8000 可以首先找到满足条件的第一个值的位置索引: idx =

我有一个数据集,一旦超过某个值,我就需要对其进行筛选,但不能在之后进行筛选。以下是数据帧的一个示例:

    Dip    MD
0   70      5000
1   80      6000
2   90      7000
3   80      8000
我想在Dip第一次超过85之前过滤掉所有内容,因此生成的数组应该如下所示:

    Dip     MD
0   90      7000
1   80      8000

可以首先找到满足条件的第一个值的位置索引:

idx = next(iter(np.where(df['Dip'] > 85)[0]), df.shape[0])
然后从该值开始按整数位置对数据帧进行切片:

res = df.iloc[idx:]
如果您的条件从未满足,则选择
df.shape[0]
作为默认值可确保在此场景中返回整个数据帧

性能说明

对于较大的数据集,您可能会发现整数索引比布尔索引更有效:

np.random.seed(0)

df = pd.DataFrame({'A': np.random.randint(0, 100, 10**6)})

%timeit df[df['A'].gt(90).cummax()]                                   # 36.1 ms
%timeit df.iloc[next(iter(np.where(df['A'] > 90)[0]), df.shape[0]):]  # 4.04 ms
如果效率是主要问题,请参阅。这样做的目的是,如果先前满足条件,则不必遍历整个序列。

可以使用

In [71]: df = pd.DataFrame({'Dip': [70, 80, 90, 80], 
    ...:     'MD': [5000, 6000, 7000, 8000]})         

In [72]: df[df.Dip.gt(85).cummax()]                   
Out[72]: 
   Dip    MD
2   90  7000
3   80  8000