您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

大熊猫索引的意义是什么?

大熊猫索引的意义是什么?

像字典一样,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.

其他 2022/1/1 18:39:41 有534人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶