删除 pandas 数据框中具有相同值的连续行

Deleting consecutive rows in a pandas dataframe with the same value

如何仅删除 pandas 数据框中具有相同值的三个连续行(在下面的示例中,这将是整数“4”)。

考虑以下代码:

import pandas as pd

df = pd.DataFrame({
    'rating': [4, 4, 3.5, 15, 5 ,4,4,4,4,4 ]
})

   rating
0  4.0
1  4.0
2  3.5
3  15.0
4  5.0
5  4.0
6  4.0
7  4.0
8  4.0
9  4.0

我想得到以下结果作为输出,其中包含值“4”的三个连续行被删除:

0  4.0
1  4.0
2  3.5
3  15.0
4  5.0
5  4.0
6  4.0

使用GroupBy.cumcount for counter and filter in rows in boolean indexing:

#filter consecutive groups less like 2 (python count from 0)
df= df[df.groupby(df['rating'].ne(df['rating'].shift()).cumsum()).cumcount().lt(2)]
print (df)
   rating
0     4.0
1     4.0
2     3.5
3    15.0
4     5.0
5     4.0
6     4.0

每次有新值存在时先获取一个组,然后使用GroupBy.head

new_df = df.groupby(df['rating'].ne(df['rating'].shift()).cumsum()).head(2)
print(new_df)

   rating
0     4.0
1     4.0
2     3.5
3    15.0
4     5.0
5     4.0
6     4.0