我已經確定了一個大熊貓命令pandas df.loc [z,x] = y如何提高速度?
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 - 但可悲的是,不支持熊貓呢。
任何想法如何加快填充二維數組?
謝謝!
編輯:對不起,沒有提到 - '時間序列' 是一個數據幀太:
timeseries = pd.DataFrame({"name": titles}, index=index)
我不知道什麼樣的對象'timeseries'是。但是,如果它有'.loc'方法,它可能有'.at'方法。如果你在特定的位置分配,'.at'應該更快。 – piRSquared
編輯:對不起,沒有提到:時間序列是一個數據幀: timeseries = pd.DataFrame({「name」:titles},index = index) 我已經添加到OP現在。 – AltSheets
我將研究這個.at函數。非常感謝,@piRSquared – AltSheets