提取两个特定细胞熊猫之间的行

时间:2020-04-17 14:27:30

标签: python-3.x pandas extract rows

我需要从列epic的单元格storycol2之间提取n行。

这是我的输入内容

import pandas as pd
df = pd.DataFrame({'col1': ['aze ', 'az a', 'az a', 'azs abv','aze ', 'az a', 'azs abv', 'abc 45','wqas', 'foo bar abc', 'foo abv', 'abc 45', 'abc 45'], 'col2': ['epic', 'ac4', 'ac5', 'story','story', 'ac10', 'ac6', 'epic','ac11', 'ac1', 'ac2', 'ac3', 'story'], 'col3': ['hey', 'hello', 'hola', 'yoopy','hawdi', 'yiiha', 'yow', 'yalla', 'yiiha', 'yow', 'yalla', 'yalla', 'yalla']})  
print(df) 

           col1   col2   col3
0          aze    epic    hey
1          az a    ac4  hello
2          az a    ac5   hola
3       azs abv  story  yoopy
4          aze   story  hawdi
5          az a   ac10  yiiha
6       azs abv    ac6    yow
7        abc 45   epic  yalla
8          wqas   ac11  yiiha
9   foo bar abc    ac1    yow
10      foo abv    ac2  yalla
11       abc 45    ac3  yalla
12       abc 45  story  yalla

这是所需的输出:

          col1    col2    col3
0         az a     ac4    hello
1         az a     ac5    hola
2         wqas     ac11   yiiha
3   foo bar abc    ac1    yow
4       foo abv    ac2    yalla
5        abc 45    ac3    yalla

@ansev提出的解决方案给了我这个输出:

       col1   col2   col3
0     az a    ac4  hello
1     az a    ac5   hola
2     aze   story  hawdi
3     az a   ac10  yiiha
4  azs abv    ac6    yow
5   abc 45  story  yalla

1 个答案:

答案 0 :(得分:1)

IIUC,boolean indexingSeries.mod 在将第一个<View> <Text>{JSON.stringify(data)}</Text> </View> 之前的所有值都设置为False之后,检测从史诗到故事的变化。

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)