【发布时间】:2016-10-11 23:43:32
【问题描述】:
我已经确定了一个 pandas 命令
timeseries.loc[z, x] = y
负责迭代中花费的大部分时间。现在我正在寻找更好的方法来加速它。循环甚至不包括 50k 个元素(生产目标是 ~250k 或更多),但已经需要一个悲伤的 20 秒。
这是我的代码(忽略上半部分,它只是计时助手)
def populateTimeseriesTable(df, observable, timeseries):
"""
Go through all rows of df and
put the observable into the timeseries
at correct row (symbol), column (tsMean).
"""
print "len(df.index)=", len(df.index) # show number of rows
global bf, t
bf = time.time() # set 'before' to now
t = dict([(i,0) for i in range(5)]) # fill category timing with zeros
def T(i):
"""
timing helper: Add passed time to category 'i'. Then set 'before' to now.
"""
global bf, t
t[i] = t[i] + (time.time()-bf)
bf = time.time()
for i in df.index: # this is the slow loop
bf = time.time()
sym = df["symbol"][i]
T(0)
tsMean = df["tsMean"][i]
T(1)
tsMean = tsFormatter(tsMean)
T(2)
o = df[observable][i]
T(3)
timeseries.loc[sym, tsMean] = o
T(4)
from pprint import pprint
print "times needed (total = %.1f seconds) for each command:" % sum(t.values())
pprint (t)
return timeseries
有(不重要,不慢)
def tsFormatter(ts):
"as human readable string, only up to whole seconds"
return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(ts))
。 .
--> 待优化代码在for循环中。
(T, 和 t 只是辅助函数和字典,用于计时。)
我已经为每一步计时。绝大多数时间:
len(df.index)= 47160
times needed (total = 20.2 seconds) for each command:
{0: 1.102,
1: 0.741,
2: 0.243,
3: 0.792,
4: 17.371}
花费在最后一步
timeseries.loc[sym, tsMean] = o
我已经下载并安装了 pypy - 但遗憾的是,它还不支持 pandas。
任何想法如何加快填充二维数组?
谢谢!
编辑:抱歉,没有提到 - 'timeseries' 也是一个数据框:
timeseries = pd.DataFrame({"name": titles}, index=index)
【问题讨论】:
-
不知道
timeseries是什么对象。但是,如果它有一个“.loc”方法,它可能有一个.at方法。如果您在特定位置分配,.at应该更快。 -
编辑:抱歉,没有提到:timeseries 是一个数据框:timeseries = pd.DataFrame({"name":titles}, index=index) 我现在已将其添加到 OP。
-
我将研究那个 .at 函数。非常感谢,@piRSquared
标签: python pandas optimization time-series