python - 在 CSV 中搜索匹配字段并使用初始日期

标签 python csv duplicates

我正在尝试在 CSV 文件中搜索具有重复设备名称的行。输出应记录第一个匹配行的日期,并记录找到的最后一行的日期。我需要一些有关从 CSV 文件中删除重复设备名称的逻辑方面的帮助,同时还要记录设备首次和最后一次出现的时间。

import time as epoch

# AlertTime, DeviceName, Status
Input = [['14/08/2016 13:00', 'device-A', 'UP'], ['14/08/2016 13:15', 'device-B', 'DOWN'], ['15/08/2016 17:30', 'device-A', 'UP']]

# FirstSeen, LastSeen, DeviceName, Status
Output = []

# Last 48 hours
now = epoch.time()
cutoff = now - (172800)

for i in Input:
    AlertTime = epoch.mktime(epoch.strptime(i[0], '%d/%m/%Y %H:%M'))
    if AlertTime > cutoff:
        Result = [i[0], i[0], i[1], i[2]]
        Output.append(Result)

print(Output)

输出(3 个条目):

[['14/08/2016 13:00', '14/08/2016 13:00', 'device-A', 'UP'], ['14/08/2016 13:15', '14/08/2016 13:15', 'device-B', 'DOWN'], ['15/08/2016 17:30', '15/08/2016 17:30', 'device-A', 'UP']]

想要的输出(2 条):

[['14/08/2016 13:15', '14/08/2016 13:15', 'device-B', 'DOWN'], ['14/08/2016 13:00', '15/08/2016 17:30', 'device-A', 'UP']]

最佳答案

您可以使用 OrderedDict 来保留设备在 CSV 文件中显示的顺序。字典用于自动删除重复项。

下面的工作原理是尝试更新现有的字典条目,如果该条目尚不存在,Python 会生成一个 KeyError 异常。在这种情况下,可以添加具有相同开始和结束警报时间的新条目。更新条目时,现有的 first_seen 用于使用最新找到的 alert_timestatus 来更新条目。最后,字典被解析以创建您所需的输出格式:

from collections import OrderedDict

# AlertTime, DeviceName, Status
input_data = [['14/08/2016 13:00', 'device-A', 'UP'], ['14/08/2016 13:15', 'device-B', 'DOWN'], ['15/08/2016 17:30', 'device-A', 'UP']]

entries = OrderedDict()

for alert_time, device_name, status in input_data:
    try:
        entries[device_name] = [entries[device_name][0], alert_time, status]
    except KeyError as e:
        entries[device_name] = [alert_time, alert_time, status]

# Convert the dictionary of entries into the required format        
output_data = [[device_name, first_seen, last_seen, status] for device_name, [first_seen, last_seen, status] in entries.items()]

print(output_data)

给你输出:

[['device-A', '14/08/2016 13:00', '15/08/2016 17:30', 'UP'], ['device-B', '14/08/2016 13:15', '14/08/2016 13:15', 'DOWN']]

关于python - 在 CSV 中搜索匹配字段并使用初始日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38951638/

相关文章:

csv - Gnuplot 统计数据无法按预期工作 : max value not right

Java:将对象包装在某种类型的集合中以存储集合中的重复项

duplicates - 如何从Lucene索引中获取唯一结果?

Python:替换文件中以模式开头的行

python - Kivy无法正确获取button.text值

php - 使用 fputcsv 将 BOM 添加到 CSV 文件

MySQL 使用唯一约束更新 sort_order 字段会导致违反唯一约束

python - 基于时间戳值流式传输和处理数据(使用 Kafka 和 Spark Streaming)

python - 与 distutils 共享库依赖项

python - Matplotlib 和 Pandas 改变负值的颜色