Pandas once condition is met in column delete n rows then go to next section

Viewed 95

I have a DataFrame df = pd.DataFrame({'col1': [.8,.9,1,1,1,.9,.7,.9,1,1,.8,.8,.9]}) which looks like

  col1
0   0.8
1   0.9
2   1.0
3   1.0
4   1.0
5   0.9
6   0.7
7   0.9
8   1.0
9   1.0
10  0.8
11  0.8
12  0.9

Once a 1 is located in col1 I want the code to remove three numbers below. It should remove the three and then look to see if there are any 1's below. The output should look like...

  col1
0   0.8
1   0.9
2   1.0
6   0.7
7   0.9
8   1.0
12  0.9

I asked a prior question and the answer said.

integers = np.r_[: df.twofour.eq(1).idxmax() + 1, 
             range(df.twofour.eq(1).idxmax() + 30, len(df))
            ]

df = df.iloc[integers]

This code can remove the first intence of a 1, can I have help expanding this for all 1's that are not removed? Are there more elegant ways to do this?

1 Answers

you can just iterate over your dataframe and get all indexes to delete:

index_to_delete = []
for row in df.itertuples():
    idx = row[0]
    value = row.col1
    if value == 1 and idx not in index_to_delete:
        index_to_delete += [idx+1, idx+2, idx+3]

df = df.loc[~df.index.isin(index_to_delete)]
print(df)

Output:

    col1
0   0.8
1   0.9
2   1.0
6   0.7
7   0.9
8   1.0
12  0.9
Related