提取两个特定的 pandas 细胞之间的行 [英] Extract rows between two specific cells pandas
本文介绍了提取两个特定的 pandas 细胞之间的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从列col2
中提取单元格epic
和story
之间的n行.
I need to extract n rows between the cells epic
and story
from the column col2
.
这是我的输入:
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提出的解决方案给了我这个输出:
the solution proposed by @ansev gave me this output instead:
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
推荐答案
IIUC, boolean indexing
与 Series.mod
在将所有值都设置为第一个epic
之前的False
之后,检测从史诗到故事的变化.
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)
输出
col1 col2 col3
0 az a ac hello
1 azs abv ac hola
这篇关于提取两个特定的 pandas 细胞之间的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文