gpt4 book ai didi

python Pandas : What causes slowdown in different column selection methods?

转载 作者:太空宇宙 更新时间:2023-11-04 09:12:19 25 4
gpt4 key购买 nike

看到this question之后关于在 Pandas 中复制类似 SQL 选择语句的行为,我添加了 this answer显示可以缩短 the accepted answer 中给出的冗长语法的两种方法对那个问题。

在试用它们之后,我的两个语法较短的方法明显变慢了,我希望有人能解释为什么

您可以假设下面使用的任何函数来自 Pandas、IPython 或来自 the question and answers linked above .

import pandas
import numpy as np
N = 100000
df = pandas.DataFrame(np.round(np.random.rand(N,5)*10))

def pandas_select(dataframe, select_dict):
inds = dataframe.apply(lambda x: reduce(lambda v1,v2: v1 and v2,
[elem[0](x[key], elem[1])
for key,elem in select_dict.iteritems()]), axis=1)
return dataframe[inds]



%timeit _ = df[(df[1]==3) & (df[2]==2) & (df[4]==5)]
%timeit _ = df[df.apply(lambda x: (x[1]==3) & (x[2]==2) & (x[4]==5), axis=1)]

import operator
select_dict = {1:(operator.eq,3), 2:(operator.eq,2), 4:(operator.eq,5)}
%timeit _ = pandas_select(df, select_dict)

我得到的输出是:

In [6]: %timeit _ = df[(df[1]==3) & (df[2]==2) & (df[4]==5)]
100 loops, best of 3: 4.91 ms per loop

In [7]: %timeit _ = df[df.apply(lambda x: (x[1]==3) & (x[2]==2) & (x[4]==5), axis=1)]
1 loops, best of 3: 1.23 s per loop

In [10]: %timeit _ = pandas_select(df, select_dict)
1 loops, best of 3: 1.6 s per loop

我可以相信 reduceoperator 函数的用户,以及我的 pandas_select 函数的函数开销可能会减慢它的速度。但这似乎过分了。在我的函数内部,我使用了相同的语法,df[key] logical_op value,但速度要慢得多。

我也很困惑,为什么沿 axis=1apply 版本要慢得多。从字面上看,它应该只是语法的缩写,不是吗?

最佳答案

当你写 df[df.apply(lambda x: (x[1]==3) & (x[2]==2) & (x[4]==5), axis= 1)],您正在为数据框中的 100000 行中的每一行调用 lambda。这会产生大量开销,因为必须为每一行执行 Python 方法调用。

当您编写 df[(df[1]==3) & (df[2]==2) & (df[4]==5)] 时,没有开销;相反,该操作在单个操作中应用于每一列,并且循环在具有矢量化潜力的 native 代码中执行(例如 SSE)。

这不是 Pandas 独有的;一般来说,如果您将数组和矩阵放在一起处理,而不是调用 Python 函数或对单个项目进行内部循环,那么任何 numpy 操作都会快得多。

关于 python Pandas : What causes slowdown in different column selection methods?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13457335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com