Python 如何按最新时间对csv文件列进行排序
我试图读取一个csv文件,它是运行autorunc命令行(即autorunc-a-m-c>mycsv.csv)的结果,并按时间对其进行排序,这样我可以像在excel中一样在顶部获得最新的日期/时间 到目前为止,我已经找到了如何将其转换为csv文件而不出现编码错误,方法是使用python类将其读入UTF16,然后将其重新编码为UTF8Python 如何按最新时间对csv文件列进行排序,python,date,sorting,csv,time,Python,Date,Sorting,Csv,Time,我试图读取一个csv文件,它是运行autorunc命令行(即autorunc-a-m-c>mycsv.csv)的结果,并按时间对其进行排序,这样我可以像在excel中一样在顶部获得最新的日期/时间 到目前为止,我已经找到了如何将其转换为csv文件而不出现编码错误,方法是使用python类将其读入UTF16,然后将其重新编码为UTF8 import sys import csv import operator import codecs class Recoder(object): de
import sys
import csv
import operator
import codecs
class Recoder(object):
def __init__(self, stream, decoder, encoder, eol='\r\n'):
self._stream = stream
self._decoder = decoder if isinstance(decoder, codecs.IncrementalDecoder) else codecs.getincrementaldecoder(decoder)()
self._encoder = encoder if isinstance(encoder, codecs.IncrementalEncoder) else codecs.getincrementalencoder(encoder)()
self._buf = ''
self._eol = eol
self._reachedEof = False
def read(self, size=None):
r = self._stream.read(size)
raw = self._decoder.decode(r, size is None)
return self._encoder.encode(raw)
def __iter__(self):
return self
def __next__(self):
if self._reachedEof:
raise StopIteration()
while True:
line,eol,rest = self._buf.partition(self._eol)
if eol == self._eol:
self._buf = rest
return self._encoder.encode(line + eol)
raw = self._stream.read(1024)
if raw == '':
self._decoder.decode(b'', True)
self._reachedEof = True
return self._encoder.encode(self._buf)
self._buf += self._decoder.decode(raw)
next = __next__
def close(self):
return self._stream.close()
writer = open('mycsv1.csv, 'wb')
f = open('mycsv.csv','rb'):
sr = Recoder(f, 'utf-16', 'utf-8')
s = sorted(csv.reader(sr), key=operator.itemgetter(0), reverse=True))
for row in s:
print >> writer, row[0], ",", row[1], "," row[2]
问题是,从外观上看,这只是按月份进行排序。假设我有2010年、2011年、2012年1-6个月的参赛作品
它只按月份排序,不包括时间或日期,这样我就只能得到最新的日期。相反,我得到的是2010年1月1日、2011年1月1日、2012年1月1日、2010年2月1日、2011年2月1日、2012年2月1日
如果我在excel中进行排序,它将首先为我提供最新的日期/时间,如果它是基于6月(2012年6月1日、2012年5月1日、2012年4月1日等)的话,我将非常感谢您对如何使用python实现这一点的任何帮助
更新
我正在处理的示例数据是从Autorunc格式化为utf8后得到的。CSV中的数据应如下所示:
Time, Entry Location, Entry, Enabled, Category, Description, Publisher, Launch String
6/23/2011 14:23, HKLM\System\CurrentControlSet\Services, JavaQuickStarterService, enabled, Services, Prefetches JRE files for faster startup, Oracle Corporation, C:\Program Files\java, C:\Program Files\Java\jre\blah
5/25/2006 1:14,,,,,,,,,
4/4/2003 22:10,,,,,,,,,
4/17/2006 11:11,,,,,,,,
0,,,,,,,,, (Some of the entries do not have date values and are null or blank.
6/10/2013 9:30,,,,,,,,,
6/23/2013 10:25,,,,,,,,,
etc
大多数条目都有值,但我不想复制和粘贴所有内容。我基本上希望像excel一样从最新的日期/时间中排序日期。下面提到的lambda选项出错了,因为它首先从列中读取“时间”。我想知道如何跳过第一行,并在其他日期/时间值上使用lambda进行适当排序。好的,我不完全理解之前发生的事情。您的问题是,您的“日期”仍然是字符串,并按字符串排序。我猜您的日期格式是月/日/年(美国日期样式),正如您所说,它是按月排序的。您所需要做的就是将日期解析为datetime对象,以解决排序问题
# add this import at the top of your file
from datetime import datetime
# replace your current call to sorted with:
s = sorted(csv.reader(sr), key=lambda x:datetime.strptime(x[0],"%m/%d/%Y"), reverse=True))
您可以使用pandas模块和to_datetime()方法 代码:
import pandas as pd
data = pd.read_csv('mycsv.csv')
data['Time'] = pd.to_datetime(data['Time'], format="%m/%d/%Y %H:%M")
data = data.sort_values(by='Time', ascending=False)
print(data.to_csv(index=False))
输入:mycsv.csv
Time, Field
6/23/2011 14:23, ABC
5/25/2006 1:14, XYZ
4/4/2003 22:10, PQR
4/17/2006 11:11,GHI
, 0
, 1
6/10/2013 9:30, 2
6/23/2013 10:25, 3
输出:
Time, Field
2013-06-23 10:25:00, 3
2013-06-10 09:30:00, 2
2011-06-23 14:23:00, ABC
2006-05-25 01:14:00, XYZ
2006-04-17 11:11:00,GHI
2003-04-04 22:10:00, PQR
, 0
, 1
如果csv本身没有排序,而Autorunc没有对输出进行排序的选项,那么您必须读取整个文件,然后用Python进行排序。这就是我现在要做的,请参阅上面的代码,但我得到的结果是按月份排序。我希望能像excel一样,通过最新版本将其整理好。我没有真正理解这个问题。日期/时间字段是CSV中的一列吗?如果是这样的话,这应该是直截了当的。逐行读取CSV(
,用于文件中的行(filename).readlines()
),在逗号处拆分每行(line.split('),')
),以创建字符串列表。现在,您可以将日期/时间列转换为datetime
字段,并使用sorted
。是的,这些字段位于顶部的CSV中。我将更新上面的内容,以便更容易理解我想要实现的目标。我以前看到过这个选项,但是如何跳过列的名称呢?例如,自动运行程序生成csv文件,每个列都有一个标题。第一列的名字是“Time”,所以如果我按照你上面的建议去做,它会返回给我一个读取“Time”值的错误,因为它是该列的第一个值。如何跳过该值并专注于实际的日期/时间值?@user2292661因此在lambda中,x[0]
只引用行中的第一列。只要用日期所在的列替换0即可。如果您可以提供csv中的示例行,这将非常有帮助。我之所以选择0,是因为您使用的是itemgetter(0)