簡體   English   中英

Python在csv文件中合並重疊的時間范圍

[英]Python combine overlapping time ranges in csv file

我正在嘗試使用python遍歷一個csv文件,找到重疊的時間范圍,然后在最后一列中求和相應的每秒帶寬(bps)值。 生成的csv文件應指示每個時間段消耗了多少帶寬或bps。

源文件具有以下格式; 開始時間,結束時間,Proto,SrcIP,DstIP,bps 00:06:01,00:06:02,TCP,10.33.239.176,172.16.168.7,699619 00:06:01,00:06:02,ICMP, 10.33.236.247,172.16.171.254,0 00:06:01,00:06:02,UDP,10.33.238.55,172.16.175.253,12473 03:10:02,03:10:02,UDP,10.33.238.55, 172.16.160.2,25 03:10:02,03:10:02,TCP,10.33.236.59,172.16.168.9,5

生成的csv文件應采用以下格式; 開始時間,結束時間,bps 00:06:01,00:06:02,712092 03:10:02,03:10:02,30

我是python新手,並嘗試使用字典刪除重復項。 我相信有更好的方法可以做到這一點...

這是我的無效代碼;

import csv

src_file = open('c:/test/format1.csv', 'rb')
dst_file = open('c:/test/format2.csv', 'wb')
reader = csv.reader(src_file)
writer = csv.writer(dst_file,delimiter=',')

dict1 = {}
dict2 = {}
dkey = 1

# read csv values into dict1
for row in reader:
    start = row[0]
    end = row[1]
    bps = int(row[7])
    dkey += 1
    dict1[dkey] = [start, end, bps]

# read dict1 results into a new dict2 removing duplicates and summing the bps column
for k, v in dict2.items():
    if v[0] and v[1] in v:
        dict2[k] = [v[0], v[1]]
        dict2[k] += [v[2]]
    else:
        dict2[k] = [v]

print dict2

代碼返回:{}

謝謝。

看起來您可能正在使它變得比所需的要復雜一些。。。如果重疊時間戳意味着完全相同(這是您的代碼所假設的),那么您可以簡單地使用時間戳作為字典的鍵,然后將bps相加(行[5])。 使用defaultdict(int)可以方便地將鍵的默認值自動設置為0:

from collections import defaultdict

dict1 = defaultdict(int)
# read csv values into dict1
for row in reader:
    dict1[(row[0], row[1])] += int(row[5])

print(dict(dict1))

輸出:

{('00:06:01', '00:06:02'): 712092, ('03:10:02', '03:10:02'): 30}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM