Remove rows from Dataframe where row above or below has same value in a specific column

Viewed 166

Starting Dataframe:

     A    B
0    1    1
1    1    2
2    2    3
3    3    4
4    3    5
5    1    6
6    1    7
7    1    8
8    2    9

Desired result - eg. Remove rows where column A has values that match the row above or below:

     A    B
0    1    1
2    2    3
3    3    4
5    1    6
8    2    9
1 Answers

You can use boolean indexing, the following condition will return true if value of A is NOT equal to value of A's next row

new_df = df[df['A'].ne(df['A'].shift())]

    A   B
0   1   1
2   2   3
3   3   4
5   1   6
8   2   9
Related