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

发布于 2025-01-09 01:47:14 字数 381 浏览 4 评论 0原文

如何仅删除 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

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").

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:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暖树树初阳… 2025-01-16 01:47:14

每次存在新值时首先获取一个组,然后使用 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

first get a group each time a new value exists, then use 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
随遇而安 2025-01-16 01:47:14

使用 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

Use 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文