我有一长串日期字符串,例如['2011-01-01', '2015-05-05']。在n个字符串的列表中,我需要选择第i个字符串并找到第i:n个字符串的最新日期。我可以做到这一点,但是这个过程很慢,一个包含数十万个字符串的列表需要几个小时。 我缺少哪些代码优化?示例代码如下。
import numpy as np
d = np.random.choice(xrange(0, 1000), size=100000, replace=True).tolist()
d = [str(item) for item in d]
total = len(d)
for i in xrange(total):
this_slice = d[i:total]
greatest = max(this_slice)
if i % 1000 == 0: # To track progress
print i
这些示例足够快。使用实际的日期字符串,而不是示例中的数字字符串,要慢得多。我已经精确地安排了执行时间,但 600,000 个日期字符串似乎需要大约 30-60 分钟。
这是我的数据代码的更精确表示:
import pandas as pd
i = 0
rows = df.shape[0]
for date in df['date']: # date is 'YYYY-MM-DD'
this_slice = df['date'][i:rows]
df['new_date'] = max(this_slice)
if i % 1000 == 0: # To track progress
print i
i += 0
我已将日期字符串转换为日期时间对象,使它们成为整数(首先删除了“-”),速度并没有更快。一定有更快的方法来编写这段代码!
最佳答案
如果你从头到尾计算,算法会更有效,这样你就可以重用最大值:
import numpy as np
d = np.random.choice(xrange(0, 1000), size=100000, replace=True).tolist()
d = [str(item) for item in d]
total = len(d)
greatest = d[total-1]
for i in reversed(xrange(total)):
greatest = max(greatest, d[i])
if i % 1000 == 0: # To track progress
print i
关于Python 迭代切片日期字符串列表的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34216037/