2014-12-22 99 views
8

试试这个自己:为什么DataFrame.loc [[1]]比df.ix [[1]]慢1800倍而比df.loc [1]慢3,500倍?

import pandas as pd 
s=pd.Series(xrange(5000000)) 
%timeit s.loc[[0]] # You need pandas 0.15.1 or newer for it to be that slow 
1 loops, best of 3: 445 ms per loop 

更新:这是a legitimate bug in pandas这是在2014年左右,8月,在0.15.1大概介绍。解决方法:在使用旧版熊猫的同时等待新版本;得到一位尖端的开发人员。来自github的版本;在pandas的版本中手动进行单行修改;暂时使用.ix而不是.loc

我有480万行的数据帧,并选择使用.iloc[[ id ]](具有单个元素的列表)的单排花费489毫秒,几乎一半的第二,比相同.ix[[ id ]]较慢1,800x倍,.iloc[id]慢3,500倍(将id作为值传递,而不是列表)。公平地说,.loc[list]需要大致相同的时间,无论列表的长度,但我不想花489毫秒就可以了,特别是当.ix是快上千倍,并产生相同的结果。据我了解,.ix应该会变慢,不是吗?

我正在使用熊猫0.15.1。 Indexing and Selecting Data的优秀教程表明.ix在某种程度上更普遍,并且推测比.loc.iloc更慢。具体而言,它说

但是,当轴是基于整数时,仅支持基于标签的访问和不支持位置访问。因此,在这种情况下,通常更好的是使用.iloc或.loc来更好地显式地使用 。

这里是一个IPython的会话与基准:

print 'The dataframe has %d entries, indexed by integers that are less than %d' % (len(df), max(df.index)+1) 
    print 'df.index begins with ', df.index[:20] 
    print 'The index is sorted:', df.index.tolist()==sorted(df.index.tolist()) 

    # First extract one element directly. Expected result, no issues here. 
    id=5965356 
    print 'Extract one element with id %d' % id 
    %timeit df.loc[id] 
    %timeit df.ix[id] 
    print hash(str(df.loc[id])) == hash(str(df.ix[id])) # check we get the same result 

    # Now extract this one element as a list. 
    %timeit df.loc[[id]] # SO SLOW. 489 ms vs 270 microseconds for .ix, or 139 microseconds for .loc[id] 
    %timeit df.ix[[id]] 
    print hash(str(df.loc[[id]])) == hash(str(df.ix[[id]])) # this one should be True 
    # Let's double-check that in this case .ix is the same as .loc, not .iloc, 
    # as this would explain the difference. 
    try: 
     print hash(str(df.iloc[[id]])) == hash(str(df.ix[[id]])) 
    except: 
     print 'Indeed, %d is not even a valid iloc[] value, as there are only %d rows' % (id, len(df)) 

    # Finally, for the sake of completeness, let's take a look at iloc 
    %timeit df.iloc[3456789] # this is still 100+ times faster than the next version 
    %timeit df.iloc[[3456789]] 

输出:

The dataframe has 4826616 entries, indexed by integers that are less than 6177817 
df.index begins with Int64Index([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], dtype='int64') 
The index is sorted: True 
Extract one element with id 5965356 
10000 loops, best of 3: 139 µs per loop 
10000 loops, best of 3: 141 µs per loop 
True 
1 loops, best of 3: 489 ms per loop 
1000 loops, best of 3: 270 µs per loop 
True 
Indeed, 5965356 is not even a valid iloc[] value, as there are only 4826616 rows 
10000 loops, best of 3: 98.9 µs per loop 
100 loops, best of 3: 12 ms per loop 
+0

注意,使用'[[ID]'和'[ID]'是不等价的。 '[id]'会返回一个Series,但'[[id]]'将返回一行DataFrame。 – BrenBarn

+0

@BrenBarn,是的,这解释了'.ix'的差异:141μs与270μs。但为什么'.loc [[id]]'这么慢? – osa

回答

6

貌似这个问题是不存在的大熊猫0.14。我用line_profiler来描述它,我想我知道发生了什么。由于熊猫0.15.1,如果给定的索引不存在,现在会产生一个KeyError。看起来像当你使用.loc[list]语法时,即使找到它,它也会沿着整个轴对索引进行彻底搜索。也就是说,首先,在发现元素的情况下不存在提前终止,其次,在这种情况下的搜索是蛮力的。

File: .../anaconda/lib/python2.7/site-packages/pandas/core/indexing.py

1278              # require at least 1 element in the index 
    1279   1   241 241.0  0.1    idx = _ensure_index(key) 
    1280   1  391040 391040.0  99.9    if len(idx) and not idx.isin(ax).any(): 
    1281           
    1282               raise KeyError("None of [%s] are in the [%s]" % 
4

熊猫索引是疯狂慢,我切换到numpy的索引

df=pd.DataFrame(some_content) 
# takes forever!! 
for iPer in np.arange(-df.shape[0],0,1): 
    x = df.iloc[iPer,:].values 
    y = df.iloc[-1,:].values 
# fast!   
vals = np.matrix(df.values) 
for iPer in np.arange(-vals.shape[0],0,1): 
    x = vals[iPer,:] 
    y = vals[-1,:]