熊猫 - 极其缓慢

cof*_*ant 0 python performance pandas

我想在日期对象上做一个df.apply,但它太慢了!

我的修剪输出给....

 ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1999   14.563    0.007   14.563    0.007 {pandas.tslib.array_to_timedelta64}
 13998    0.103    0.000   15.221    0.001 series.py:126(__init__)
  9999    0.093    0.000    0.093    0.000 {method 'reduce' of 'numpy.ufunc' objects}
272012    0.093    0.000    0.125    0.000 {isinstance}
  5997    0.089    0.000    0.196    0.000 common.py:199(_isnull_ndarraylike)
Run Code Online (Sandbox Code Playgroud)

所以基本上它是一个2000长度阵列的14秒.我的实际数组大小> 100,000,转换为运行时间> 15分钟或更长.

调用这个函数"pandas.tslib.array_to_timedelta64"这是一个瓶颈,这是熊猫的愚蠢行为吗?我真的不明白为什么这个函数调用是必要的??? 减法中的运算符都具有相同的数据类型.我明确地使用pd.to_datetime()方法转换它们.并且此计算中不包括此转换时间.

所以你可以理解我对这个可怜代码的沮丧!

实际代码看起来像这样

 df  = pd.DataFrame(bet_endtimes)

def testing():
    close_indices = df.apply(lambda x: np.argmin(np.abs(currentdata['date'] - x[0])),axis=1)
    print close_indices

 %prun testing()
Run Code Online (Sandbox Code Playgroud)

Jef*_*eff 8

我建议查阅文档:http://pandas.pydata.org/pandas-docs/stable/timeseries.html#time-deltas 它也非常有用,包括样本数据所以我不必猜测你是什么这样做.

使用apply 始终是最后一次尝试的操作.矢量化方法要快得多.

In [55]: pd.set_option('max_rows',10)

In [56]: df = DataFrame(dict(A = pd.date_range('20130101',periods=100000, freq='s')))

In [57]: df
Out[57]: 
                        A
0     2013-01-01 00:00:00
1     2013-01-01 00:00:01
2     2013-01-01 00:00:02
3     2013-01-01 00:00:03
4     2013-01-01 00:00:04
...                   ...
99995 2013-01-02 03:46:35
99996 2013-01-02 03:46:36
99997 2013-01-02 03:46:37
99998 2013-01-02 03:46:38
99999 2013-01-02 03:46:39

[100000 rows x 1 columns]

In [58]:  (df['A']-df.loc[10,'A']).abs()
Out[58]: 
0   00:00:10
1   00:00:09
2   00:00:08
...
99997   1 days, 03:46:27
99998   1 days, 03:46:28
99999   1 days, 03:46:29
Name: A, Length: 100000, dtype: timedelta64[ns]

In [59]: %timeit  (df['A']-df.loc[10,'A']).abs()
1000 loops, best of 3: 1.47 ms per loop
Run Code Online (Sandbox Code Playgroud)

当您为熊猫做贡献时,您可以为方法命名.

调用这个函数"pandas.tslib.array_to_timedelta64"这是一个瓶颈,这是熊猫的愚蠢行为吗?时间不包括在此计算中.