2017-07-05 23 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