试试这个自己:为什么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
注意,使用'[[ID]'和'[ID]'是不等价的。 '[id]'会返回一个Series,但'[[id]]'将返回一行DataFrame。 – BrenBarn
@BrenBarn,是的,这解释了'.ix'的差异:141μs与270μs。但为什么'.loc [[id]]'这么慢? – osa