首页 > 解决方案 > Pandas 多索引创建性能

问题描述

pd.MultiIndex使用不同的类方法创建相等的性能测试:

import pandas as pd

size_mult = 8
d1 = [1]*10**size_mult
d2 = [2]*10**size_mult

pd.__version__
'0.24.2'

.from_arrays, from_tuples, from_frame:

# Cell from_arrays
%%time
index_arr = pd.MultiIndex.from_arrays([d1, d2], names=['a', 'b'])
# Cell from_tuples
%%time
index_tup = pd.MultiIndex.from_tuples(zip(d1, d2), names=['a', 'b'])
# Cell from_frame
%%time
df = pd.DataFrame({'a':d1, 'b':d2})
index_frm = pd.MultiIndex.from_frame(df)

单元格的相应输出:

# from_arrays
CPU times: user 1min 15s, sys: 6.58 s, total: 1min 21s
Wall time: 1min 21s
# from_tuples
CPU times: user 26.4 s, sys: 4.99 s, total: 31.4 s
Wall time: 31.3 s
# from_frame
CPU times: user 47.9 s, sys: 5.65 s, total: 53.6 s
Wall time: 53.7 s

让我们检查一下这个案例的所有结果是否相同

index_arr.difference(index_tup)
index_arr.difference(index_frm)

所有生产线产生:

MultiIndex(levels=[[1], [2]],
           codes=[[], []],
           names=['a', 'b'])

那么为什么会有这么大的区别呢?from_arrays几乎比 . 慢 3 倍from_tuples。它甚至比创建 DataFrame 并在其上构建索引还要慢。

编辑:

我做了另一个更通用的测试,结果出人意料地相反:

np.random.seed(232)

size_mult = 7
d1 = np.random.randint(0, 10**size_mult, 10**size_mult)
d2 = np.random.randint(0, 10**size_mult, 10**size_mult)

start = pd.Timestamp.now()
index_arr = pd.MultiIndex.from_arrays([d1, d2], names=['a', 'b'])
print('ARR done in %f' % (pd.Timestamp.now()-start).total_seconds())

start = pd.Timestamp.now()
index_tup = pd.MultiIndex.from_tuples(zip(d1, d2), names=['a', 'b'])
print('TUP done in %f' % (pd.Timestamp.now()-start).total_seconds())
ARR done in 9.559764
TUP done in 70.457208

因此from_tuples,尽管源数据相同,但现在的速度要慢得多。

标签: pythonpandasperformancemulti-index

解决方案


你的第二个例子对我来说更有意义。查看 Pandas 的源代码,from_tuples实际上是调用from_arrays,所以对我来说这from_arrays会更快。

from_tuples在这里还做了一些额外的步骤,这些步骤会花费更多时间:

  1. 你传入了 a zip(d1, d2),它实际上是一个迭代器。from_tuples 将其转换为列表
  2. 将其转换为元组列表后,它会通过一个额外的步骤将其转换为 numpy 数组列表
  3. 上一步遍历元组列表两次,使得from_tuples比 明显慢from_arrays,马上。

所以总的来说,我对from_tuples速度较慢并不感到惊讶,因为它必须在你的元组列表中迭代两次(并做一些额外的事情),然后才能进入from_arrays函数(顺便说一下,它迭代了几次) ) 它无论如何都使用。


推荐阅读