pandas - Pandas - 在数据框中删除重叠范围
问题描述
具有以下形式的数据框:
df = pd.DataFrame({
'A': ('foo', 'foo', 'foo', 'foo', 'foo'),
'start': (3039, 3536, 9140, 12976, 14982),
'end': (3536, 4879, 44331, 13641, 15643)
})
A start end
0 foo 3039 3536
1 foo 3536 4879
2 foo 9140 44331
3 foo 12976 13641
4 foo 14982 15643
如何删除由start
andend
列确定的“范围”与其他行重叠的所有行?在上面的示例中,具有索引3
和的4
行将被删除,因为它们包含在行索引2
中。
我尝试从shift()
初步创建一个掩码系列开始,但除了因为所有值都是 而无法工作之外False
,它只会与前一行进行比较,而我想比较所有行的范围。
ranges_mask = ((df['start'] > df['start'].shift(-1)) & (df['end'] < df['end'].shift(-1)))
解决方案
这是一个解决方案,我们只考虑间隔完全在另一个范围内的情况:
df2=df.copy()
groups=pd.Series([1]*len(df))
while (groups.value_counts()>1).any():
groups=( df2['start'].gt(df2['start'].shift()) &
df2['end'].gt(df2['end'].shift()) ).cumsum()
print(groups)
df2=df2.groupby(groups,as_index=False).first()
print(df2)
输出
0 0
1 1
2 2
3 2
4 3
dtype: int64
0 0
1 1
2 2
3 2
dtype: int64
0 0
1 1
2 2
dtype: int64
A start end
0 foo 3039 3536
1 foo 3536 4879
2 foo 9140 44331
推荐阅读
- android - BOOT COMPLETE BroadcastReceiver 自动注册
- mysql - 如何根据 sql 使用案例中的某些特定条件获得所需的结果?
- javascript - 模板继承问题:一个模板覆盖另一个
- rest - 临时锁定资源,直到 goroutine 完成
- javascript - 将 React Web 应用程序中的图像保存到我的笔记本电脑
- r - 在 R 中缩短嵌套的`lapply(sapply())` 调用
- angular - NgRX 效果 catchError 和全局错误拦截器
- windows - 以管理员身份运行强制安装非管理员设置
- google-analytics - 为什么 GA 中的用户数存在差异?
- javascript - 乘法按钮无法执行