2017-07-05 43 views
0

我剖析一個OD我功能的時間,我看到我花了很多時間對大熊貓據幀創作 - 我說的是大約2.5秒,構建一個數據幀有1000列和10K行:may_convert_objects有什麼用?

def test(size): 
samples = [] 
for r in range(10000): 
    a,b = np.random.randint(100, size=2) 
    data = np.random.beta(a,b ,size = size) 
    samples.append(data) 
return DataFrame(samples, dtype = np.float64) 

運行%prun -l 4 test(1000)回報:

enter image description here

反正我能避免這個檢查?這真的不是似乎試圖找出這種方法和繞過這裏的方法,但沒有發現任何東西在線。

回答

0

熊貓必須反思每一行,因爲你傳遞了一個數組列表。這裏有一些更有效的方法。

In [27]: size=1000 

In [28]: samples = [] 
    ...: for r in range(10000): 
    ...:  data = np.random.beta(1,1 ,size = size) 
    ...:  samples.append(data) 
    ...: 

In [29]: np.asarray(samples).shape 
Out[29]: (10000, 1000) 

# original 
In [30]: %timeit DataFrame(samples) 
2.29 s ± 91.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 

# numpy is less flexible on the conversion, but in this case 
# it is fine 
In [31]: %timeit DataFrame(np.asarray(samples)) 
30.9 ms ± 426 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) 

# you should probably just do this 
In [32]: samples = np.random.beta(1,1, size=(10000, 1000)) 

In [33]: %timeit DataFrame(samples) 
74.4 µs ± 381 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) 
+0

嗨,這太棒了!非常感謝。關於最後一個選項..那麼,我不能這麼做,因爲每個數組都由不同的a,b參數組成。我會改變這個問題來反映這個問題,所以很明顯。再次感謝 :) – idoda