像字典一样,DataFrame的索引由哈希表支持。基于索引值查找行就像基于键查找字典值。
相反,列中的值类似于列表中的值。
基于索引值查找行比基于列值查找行要快。
例如,考虑
df = pd.DataFrame({'foo':np.random.random(), 'index':range(10000)})
df_with_index = df.set_index(['index'])
@H_404_10@
这是您如何查找df['index']@H_404_10@列等于999的任何行。Pandas必须遍历列中的每个值以找到等于999的值。
df[df['index'] == 999]
# foo index
# 999 0.375489 999
@H_404_10@
这是查找索引等于999的任何行的方式。通过索引,Pandas使用哈希值查找行:
df_with_index.loc[999]
# foo 0.375489
# index 999.000000
# Name: 999, dtype: float64
@H_404_10@
按索引查找行比按列值查找行快得多:
In [254]: %timeit df[df['index'] == 999]
1000 loops, best of 3: 368 µs per loop
In [255]: %timeit df_with_index.loc[999]
10000 loops, best of 3: 57.7 µs per loop
@H_404_10@
但是请注意,建立索引需要时间:
In [220]: %timeit df.set_index(['index'])
1000 loops, best of 3: 330 µs per loop
@H_404_10@
因此,只有在要执行许多这种类型的查找时,才具有索引才是有利的。
有时,索引在重塑DataFrame中起着作用。许多功能,如set_index@H_404_10@,
stack@H_404_10@,
unstack@H_404_10@,
pivot@H_404_10@,
pivot_table@H_404_10@,
melt@H_404_10@,
lreshape@H_404_10@,和
crosstab@H_404_10@,全部使用或操纵的指数。有时候,我们希望在演示时使用,或不同形状的数据帧
join@H_404_10@,
merge@H_404_10@或
groupby@H_404_10@操作。(正如您记加盟也可以根据列值来完成,但从分道基于索引更快。)在幕后,
join@H_404_10@,
merge@H_404_10@并
groupby@H_404_10@采取快速索引查找的优势在可能的情况。
时间序列已经resample@H_404_10@,
asfreq@H_404_10@并且
interpolate@H_404_10@其基本实现拍摄快速索引查找的优势太方法。
So in the end, I think the origin of the index’s usefulness, why it shows up in so many functions, is due to its ability to perform fast hash lookups.