given a big dataframe, how can I remove all the things between two specific strings, here "start" and "end". Yesteday, I asked a similar question but removing the two strings (I post my solution here below). Now I would like to see how I can keep also the strings. I have been trying to get the next row using itertuples, but I still haven't figured out how to do it.
df1:
c1 c2
0 1 1
1 2 start
2 3 3
3 4 end
4 5 5
5 6 start
6 7 end
7 8 0
code to remove strings and things in between:
df = pd.DataFrame(
{'c1': [1, 2, 3, 4, 5, 6, 7, 8],
'c2': ['1', 'start', '3', 'end',
'5', 'start', 'end', 0]})
df2 = copy.copy(df)
flag = False
list_a = []
for j in df.itertuples():
if j.c2 == 'start':
flag = True
list_a.append((j))
elif j.c2 =='end':
flag = False
list_a.append((j))
elif flag:
list_a.append((j))
list_a = tuple(list_a)
to_remove_df = pd.DataFrame(list_a, columns=['index','c1','c2'])
to_remove_df = to_remove_df["c2"]
removed_df = pd.merge(df, to_remove_df, on=["c2"], how="outer", indicator=True).query('_merge != "both"').drop('_merge', 1)
output df2:
c1 c2
0 1 1
4 5 5
7 8 0
Wanted output:
df1:
c1 c2
0 1 1
1 2 start
3 4 end
4 5 5
5 6 start
6 7 end
7 8 0