删除数据框中每个id的前n行。

3

我有一个DataFrame,其中有两列。我想删除每个id的前3行数据。如果id少于或等于3行,则也删除这些行。如下所示,id为3和1有3和2行,因此它们应该被删除。对于id 4和2,仅保留第4、5行。

import pandas as pd
df = pd.DataFrame()
df ['id'] = [4,4,4,4, 4,2, 2,2,2,2,3,3,3, 1, 1]
df ['value'] = [2,1,1,2, 3, 4, 6,-1,-2,2,-3,5,7, -2, 5]

这是我想要的DataFrame。

enter image description here

3个回答

3
使用groupby+cumcount给每个"id"编号,并过滤掉编号大于2的行:
out = df[df.groupby('id').cumcount() > 2]

输出:

   id  value
3   4      2
4   4      3
8   2     -2
9   2      2

0
使用Series.value_countsSeries.map来执行布尔索引。
new_df = df[df['id'].map(df['id'].value_counts().gt(2))]

   id  value
3   4      2
4   4      3
8   2     -2
9   2      2

我无法通过上述代码获得您的示例输出,请检查一下。 - BENY

0

使用 cumcount 是一种方法,但使用 drop 也可以实现

out = df.groupby('id',sort=False).apply(lambda x : x.drop(x.index[:3])).reset_index(drop=True)
Out[12]: 
   id  value
0   4      2
1   4      3
2   2     -2
3   2      2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接