Extract rows between two specific cells pandas

前端 未结 1 1499
孤城傲影
孤城傲影 2021-01-21 19:35

I need to extract n rows between the cells epic and story from the column col2.

This is my input:

import pandas as         


        
相关标签:
1条回答
  • 2021-01-21 19:54

    IIUC,boolean indexing with Series.mod to detect the change from epic to story after setting all values ​​to False before the first epic.

    epic = df['col2'].eq('epic') 
    story = df['col2'].eq('story')
    df.loc[(epic | story).where(epic.cumsum().ge(1), False)
                         .cumsum()
                         .mod(2)
                         .eq(1)
                         .where(~epic, False)].reset_index(drop=True)
    

    Output

          col1 col2   col3
    0     az a   ac  hello
    1  azs abv   ac   hola
    
    0 讨论(0)
提交回复
热议问题