[英]Parse CSV file and modify columns
我想以特定方式更改CSV文件。 這是我的示例CSV文件:
name,time,Operations
Cassandra,2015-10-06T15:07:22.333662984Z,INSERT
Cassandra,2015-10-06T15:07:24.334536781Z,INSERT
Cassandra,2015-10-06T15:07:27.339662984Z,READ
Cassandra,2015-10-06T15:07:28.344493608Z,READ
Cassandra,2015-10-06T15:07:28.345221189Z,READ
Cassandra,2015-10-06T15:07:29.345623750Z,READ
Cassandra,2015-10-06T15:07:31.352725607Z,UPDATE
Cassandra,2015-10-06T15:07:33.360272493Z,UPDATE
Cassandra,2015-10-06T15:07:38.366408708Z,UPDATE
我知道如何使用python解析器從CSV文件讀取內容,但是我完全是一個初學者。 我需要得到這樣的輸出:
start_time,end_time,operation
2015-10-06T15:07:22.333662984Z,2015-10-06T15:07:24.334536781Z,INSERT
2015-10-06T15:07:27.339662984Z,2015-10-06T15:07:29.345623750Z,READ
2015-10-06T15:07:31.352725607Z,2015-10-06T15:07:38.366408708Z,UPDATE
注釋:開始時間是在特定查詢(插入/讀取,更新)開始時給出的時間戳,因此,結束時間是查詢完成。
謝謝。
從您的示例中可以看出,您可以(大概)保證“操作”列中某種類型的第一個條目以及該類型的最后一個條目是開始時間和停止時間。 如果您不能保證這一點,那么它會稍微復雜一些,但讓我們假設您無法做到 –更強大。
我們可以假設的一件事是,CSV中表示的數據是完整的。 如果您缺少某個特定操作的條目,那么我們無能為力。 我們還想閱讀時間戳,可以使用dateutil.parser
模塊來完成。
因此,我們可以先建立一個簡短的字典來跟蹤我們的值,再建立一個用於填充字典的函數,該函數一次接受一行。
import dateutil.parser
ops = dict()
def update_ops(opsdict, row):
# first get the timestamp and op name in a useable format
timestamp = dateutil.parser.parse(row[1])
op_name = row[2]
## now populate, or update the dictionary
if op_name not in opsdict:
# sets a new dict entry with the operation's timestamp.
# since we don't know what the start time and end time
# is yet, for the moment set them both.
opsdict[op_name] = { 'start_time': timestamp,
'end_time': timetstamp }
else:
# now evaluate the current timestamp against each start_time
# and end_time value. Update as needed.
if opsdict[op_name]['start_time'] > timestamp:
opsdict[op_name]['start_time'] = timestamp
if opsdict[op_name]['end_time'] < timestamp:
opsdict[op_name]['end_time'] = timestamp
現在,我們有了執行排序的功能,可以通過CSV文件閱讀器運行並填充ops
。 完成后,我們可以使用字典中的內容生成一個新的CSV文件。
import csv
cr = csv.reader(open('/path/to/your/file.csv'))
cr_head = cr.next() # throw away the first row
for row in cr:
update_ops(ops, row)
# Now write a new csv file – csv.writer is your friend :)
with open('new_operation_times.csv', 'w') as newcsv:
cw = csv.writer(newcsv)
# first write your header. csv.writer accepts lists for each row.
header = 'start_time,end_time,operation'.split(',')
cw.writerow(header)
# now write out your dict values. You may want them sorted,
# but how to do that has been answered elsewhere on SE.
for opname, timesdict in ops.items():
row = [ opname, timesdict['start_time'], timesdict['end_time'] ]
cw.writerow(row)
大功告成! 我已經盡力使這一過程變得更加詳盡,所以很清楚發生了什么。 您可以將其中的許多步驟分解為更少,更聰明的步驟(例如,從一個csv讀取並直接將其寫出)。 但是,如果您遵循KISS原則,那么以后您將可以更輕松地閱讀此內容,並再次學習它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.