简体   繁体   English

删除 pandas dataframe 中具有相同值的连续行

[英]Deleting consecutive rows in a pandas dataframe with the same value

How can I delete only the three consecutive rows in a pandas dataframe that have the same value (in the example below, this would be the integer "4").如何仅删除 pandas dataframe 中具有相同值的三个连续行(在下面的示例中,这将是 integer“4”)。

Consider the following code:考虑以下代码:

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

I would like to get the following result as output with the three consecutive rows containing the value "4" being removed:我想得到以下结果 output 包含值“4”的三个连续行被删除:

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

first get a group each time a new value exists, then use GroupBy.head每次存在新值时首先获取一个组,然后使用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

Use GroupBy.cumcount for counter and filter in rows in boolean indexing :boolean indexing中使用GroupBy.cumcount进行计数器和行过滤:

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM