代码之家  ›  专栏  ›  技术社区  ›  pookie

从index until条件获取数据帧中的行

  •  3
  • pookie  · 技术社区  · 7 年前

    假设我有一个熊猫数据帧:

    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
    

    现在,我想,给定一个索引,在 x 直到满足条件。 例如,如果 index = 2 :

    x.loc[2]
    Out[14]: 
    value    3
    Name: 2, dtype: int64
    

    现在我想,从那开始 index ,找到下一个 n 值大于某些值的行 threshold . 例如,如果 threshold is 0 ,结果应为:

    x
    Out[9]: 
        value
    2       3
    3       2
    4       1
    5       0
    

    x.loc[2:x['value']>0,:]
    

    但这当然行不通,因为 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
    
    2 回复  |  直到 7 年前
        1
  •  5
  •   rafaelc    7 年前

    使用 idxmin

    x.loc[2:x['value'].gt(0).idxmin(),:]
    
    2    3
    3    2
    4    1
    5    0
    Name: value
    

    编辑:

    index = 7
    threshold = 2
    x.loc[index:x.loc[index:,'value'].gt(threshold).idxmin(),:]
    

    从你在评论中的描述来看,似乎你想从 index+1 而不是索引。所以,如果是这样的话,就用

    x.loc[index+1:x.loc[index+1:,'value'].gt(threshold).idxmin(),:]
    
        2
  •  1
  •   Jake Morris    7 年前

    您要筛选大于 index=2 ,和 x['value']>=threshold n .head(n) .

    说:

    idx = 2
    threshold = 0
    n = 4
    x[(x.index>=idx) & (x['value']>=threshold)].head(n)
    

    #      value
    # 2     3
    # 3     2
    # 4     1
    # 5     0
    

    编辑:更改为>=,并更新示例以匹配OP的示例。

    编辑2由于OP的澄清:自 未知:

    idx = 2
    threshold = 0
    x.loc[idx:(x['value']<=threshold).loc[x.index>=idx].idxmax()]
    

    idx ,在这种情况下 idx=2 5 ).