pandas - 熊猫性能:列选择
问题描述
我今天观察到,选择两列或多列数据框可能比只选择一列要慢得多。
如果我使用 loc 或 iloc 选择多个列并使用 list 传递列名或索引,则与使用 iloc 选择单列或多列(但未传递列表)相比,性能下降 100 倍
例子:
df = pd.DataFrame(np.random.randn(10**7,10), columns=list('abcdefghij'))
一栏选择:
%%timeit -n 100
df['b']
3.17 µs ± 147 ns per loop (mean ± std. dev. of 7 runs, 100 loops each)
%%timeit -n 100
df.iloc[:,1]
66.7 µs ± 5.95 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%%timeit -n 100
df.loc[:,'b']
44.2 µs ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
两列选择:
%%timeit -n 10
df[['b', 'c']]
96.4 ms ± 788 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit -n 10
df.loc[:,['b', 'c']]
99.4 ms ± 4.44 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit -n 10
df.iloc[:,[1,2]]
97.6 ms ± 1.79 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
只有这个选择像预期的那样工作:[编辑]
%%timeit -n 100
df.iloc[:,1:3]
103 µs ± 17.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
机制有什么不同,为什么它们如此之大?
[编辑]:正如@run-out 所指出的,pd.Series 的处理速度似乎比 pd.DataFrame 快得多,有人知道为什么会这样吗?
另一方面 - 它没有解释df.iloc[:,[1,2]]
和之间的区别df.iloc[:,1:3]
解决方案
Pandas 以 pandas.Series 的形式处理单行或单列,这比在 DataFrame 架构中工作要快。
当您要求时,Pandas 与 pandas.Series 一起使用:
%%timeit -n 10
df['b']
2.31 µs ± 1.59 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
但是,我可以通过将它放在一个列表中来调用同一列的 DataFrame。然后你得到:
%%timeit -n 10
df[['b']]
90.7 ms ± 1.73 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
从上面可以看出,是 Series 的表现优于 DataFrame。
以下是 Pandas 处理“b”列的方式。
type(df['b'])
pandas.core.series.Series
type(df[['b']])
pandas.core.frame.DataFrame
编辑:我正在扩展我的答案,因为 OP 想要更深入地研究为什么 pd.series 与 pd.dataframe 相比速度更快。而且这是一个很好的问题,可以扩展我/我们对底层技术如何工作的理解。有比较专业的朋友请多多指教。
首先让我们从 numpy 开始,因为它是 pandas 的构建块。根据 Pandas 的作者和 Python for Data Analysis 的 Wes McKinney 的说法,numpy 的性能优于 python:
This is based partly on performance differences having to do with the
cache hierarchy of the CPU; operations accessing contiguous blocks of memory (e.g.,
summing the rows of a C order array) will generally be the fastest because the mem‐
ory subsystem will buffer the appropriate blocks of memory into the ultrafast L1 or
L2 CPU cache.
让我们看看这个例子的速度差异。让我们从数据框的“b”列创建一个 numpy 数组。
a = np.array(df['b'])
现在进行性能测试:
%%timeit -n 10
a
结果是:
32.5 ns ± 28.2 ns per loop (mean ± std. dev. of 7 runs, 10 loops each)
在 2.31 µs 的 pd.series 时间内,性能有了很大的提升。
性能提升的另一个主要原因是 numpy 索引直接进入 NumPy C 扩展,但是当你索引到 Series 时会发生很多 python 的事情,这要慢得多。(阅读这篇文章)
我们来看看为什么会这样的问题:
df.iloc[:,1:3]
大幅超越:
df.iloc[:,[1,2]]
有趣的是,在这种情况下,.loc 与 .iloc 具有相同的性能效果。
我们的第一个重要线索是有什么不对劲的地方在下面的代码中:
df.iloc[:,1:3] is df.iloc[:,[1,2]]
False
这些给出了相同的结果,但是是不同的对象。我已经进行了深入研究,试图找出其中的区别。我无法在互联网上或我的图书馆中找到对此的参考。
查看源代码,我们可以开始看到一些差异。我指的是 indexing.py。
在 _iLocIndexer 类中,我们可以找到 pandas 为 iloc 切片中的列表所做的一些额外工作。
马上,我们在检查输入时遇到了这两个区别:
if isinstance(key, slice):
return
对比
elif is_list_like_indexer(key):
# check that the key does not exceed the maximum size of the index
arr = np.array(key)
l = len(self.obj._get_axis(axis))
if len(arr) and (arr.max() >= l or arr.min() < -l):
raise IndexError("positional indexers are out-of-bounds")
仅此一项就足以导致性能下降吗?我不知道。
尽管 .loc 略有不同,但在使用值列表时也会影响性能。在 index.py 中查看 def _getitem_axis(self, key, axis=None): --> 在类 _LocIndexer(_LocationIndexer) 中:
is_list_like_indexer(key) 处理列表输入的代码部分很长,包括很多开销。它包含以下注释:
# convert various list-like indexers
# to a list of keys
# we will use the *values* of the object
# and NOT the index if its a PandasObject
当然,在处理值或整数列表时有足够的额外开销,然后直接切片导致处理延迟。
代码的其余部分超出了我的工资等级。如果有人可以看一下并按一下,那将是最受欢迎的
推荐阅读
- python - 从 pyspark 中的两个 RDD 创建基于列的数据框
- statsmodels - Python OLS with categorical label
- java - 如何在行索引和列索引处设置元素以使用链表创建稀疏矩阵
- .htaccess - 创建子目录 alias/rewrite 以删除 url 的最终目录
- python - 如何处理具有不同值的相同列标题
- php - 如何在phpunit中测试数组对象?
- javascript - 使用 express sendfile 将变量发送到 HTML(简短问题)
- google-app-engine - Google 应用引擎将流量拆分为单个版本
- amazon-web-services - 在 AWS 中隔离客户数据的最佳方法是什么
- c# - 循环遍历特定系统日期的所有文件 - C#