python - 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
,尽管源数据相同,但现在的速度要慢得多。
解决方案
你的第二个例子对我来说更有意义。查看 Pandas 的源代码,from_tuples
实际上是调用from_arrays
,所以对我来说这from_arrays
会更快。
from_tuples
在这里还做了一些额外的步骤,这些步骤会花费更多时间:
- 你传入了 a
zip(d1, d2)
,它实际上是一个迭代器。from_tuples
将其转换为列表。 - 将其转换为元组列表后,它会通过一个额外的步骤将其转换为 numpy 数组列表
- 上一步遍历元组列表两次,使得
from_tuples
比 明显慢from_arrays
,马上。
所以总的来说,我对from_tuples
速度较慢并不感到惊讶,因为它必须在你的元组列表中迭代两次(并做一些额外的事情),然后才能进入from_arrays
函数(顺便说一下,它迭代了几次) ) 它无论如何都使用。
推荐阅读
- java - Antlr4 解析器中缺少变量
- angular - RouterOutlet 魔术 ;) 带有动态参数的导航栏 routerLink?
- c++ - 将值传递给构造函数c ++的差异语法
- r - 无法通过在 Rshiny 中压缩来下载具有 excel 文件的文件夹
- python - 使用 Python 执行 GameFbxExporter Maya
- html - 浮动:右元素不与浮动:左元素内联
- wordpress - Wordpress:使用带有自定义排序的 query_posts
- machine-learning - AutoML 中的更多样本并没有产生更好的结果
- c# - 带有 luis 结果的 C# Microsoft Bot Framework 指向 QNA Maker 和图形 api
- c# - 使用 MSBuild 时,Visual Studio Android 解决方案在遇到 C# 版本冲突时停止构建