代码之家  ›  专栏  ›  技术社区  ›  Rahul Agarwal

获取特定索引后带有符号的行

  •  0
  • Rahul Agarwal  · 技术社区  · 6 年前

    我有一个df:

    Index col1
    1     Abc
    2     xyz
    3     $123
    4     wer
    5     exr
    6     ert
    7     $546
    8     $456
    

    问题陈述 :

    现在我想找到关键字后面包含美元符号的行的索引 wer .

    我的代码:

    idx = df.col1.str.contains('\$').idxmax() ## this gives me index 3 but what i want is index 7
    

    帮助需要修改我的代码以获得所需的输出

    0 回复  |  直到 6 年前
        1
  •  1
  •   Quang Hoang    6 年前

    你需要掩盖真相 wer

    s = (df['col1'].str.contains('\$')           # rows containing $
         & df['col1'].eq('wer').cumsum().gt(0)   # rows after the first 'wer'
        ).idxmax()
    # s == 7
    
        2
  •  1
  •   ansev    6 年前

    使用:

    #df=df.set_index('Index') #if 'index' is a column
    df2=df[df['col1'].eq('wer').cumsum()>0]
    df2['col1'].str.contains('\$').idxmax()
    

    或者:

    df[(df['col1'].eq('wer').cumsum()>0) & df['col1'].str.contains('\$')].index[0]
    

    输出:

    7
    

    细节:

    df['col1'].eq('wer').cumsum().eq(1)
    Index
    1    False
    2    False
    3    False
    4     True
    5     True
    6     True
    7     True
    8     True
    Name: col1, dtype: bool
    

    print(df2)
           col1
    Index      
    4       wer
    5       exr
    6       ert
    7      $546
    8      $456