python - 根据上行中的值删除时间索引 Pandas 数据框中的 n 行
问题描述
在 Pandas 上工作,需要根据列中的值删除 DataFrame 中的 n 个连续行。
在下面的示例中,在 17:00:01 有一个事件持续 2 秒。在那个时间跨度下降时,我需要以下 2 行。在 17:00:04 有另一个事件,然后应该删除第 17:00:05 行。
不确定如何处理这个问题。在 lamda 中使用遮罩?
t = pd.to_timedelta(df['EventSeconds'], unit='s')
mask = df['2019-01-07 17:00:02' : '2019-01-07 17:00:02' + t]
我有:
Index EventSeconds OtherColumn
07/01/2019 16:59:59 0 2
07/01/2019 17:00:00 2 3
07/01/2019 17:00:01 0 4
07/01/2019 17:00:02 0 5
07/01/2019 17:00:03 0 6
07/01/2019 17:00:04 1 7
07/01/2019 17:00:05 0 8
07/01/2019 17:00:06 0 9
我需要:
Index EventSeconds OtherColumn
07/01/2019 16:59:59 0 2
07/01/2019 17:00:00 2 3
07/01/2019 17:00:03 0 6
07/01/2019 17:00:04 1 7
07/01/2019 17:00:06 0 9
解决方案
您可以添加持续时间Index
以获取结束时间,但您需要使用ffill
for even with 0
seconds:
t = pd.to_timedelta(df['EventSeconds'], unit='s')
# print end_times to see details
end_times = (df['Index'].add(t) # calculate the end time
.where(df['EventSeconds'].ne(0)) # mask the starting events
.ffill() # fill the same end times
)
df[df['Index'].gt(end_times)| df['EventSeconds'].ne(0) ]
输出:
Index EventSeconds
0 2019-07-01 16:59:59 0
1 2019-07-01 17:00:00 2
4 2019-07-01 17:00:03 0
5 2019-07-01 17:00:04 1
7 2019-07-01 17:00:06 0
推荐阅读
- reactjs - 修复 react-table useTable 行的高度
- c# - 为什么 spawn 对象不在平面上工作?对象从平面区域生成。在地形上它正在工作
- node.js - 如何从node.js(电子)将大文件上传到firebase存储?
- c# - AzureKeyVault 在本地 ASP.NET 4.7.1 WebForms 应用程序中不起作用
- html - 带有修改后 alpha 的渐变不会填满整个页面
- angular - 数字通过从 Angular 客户端到 NestJS 服务器的 Http 请求转换为字符串
- java-8 - 使用流有选择地修改列表项
- swift - FSCalendar:从头开始查看标题?
- c - 使用 LLVMBuildNeg 时出现致命的 llvm 错误
- python - AWS IoT Core:能够从设备连接到 AWS,但已发布的消息未显示在控制台中并且订阅主题无限期挂起