- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
看到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
我可以相信 reduce
、operator
函数的用户,以及我的 pandas_select
函数的函数开销可能会减慢它的速度。但这似乎过分了。在我的函数内部,我使用了相同的语法,df[key] logical_op value
,但速度要慢得多。
我也很困惑,为什么沿 axis=1
的 apply
版本要慢得多。从字面上看,它应该只是语法的缩写,不是吗?
最佳答案
当你写 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/
请不要因为长篇大论而气馁。我尽量提供尽可能多的数据,我真的需要帮助解决这个问题:S。如果有新的提示或想法,我会每天更新 问题: 我尝试在并行进程的帮助下在两核机器上并行运行 Python 代码(以避免
看到this question之后关于在 Pandas 中复制类似 SQL 选择语句的行为,我添加了 this answer显示可以缩短 the accepted answer 中给出的冗长语法的两种
我已经开发了一个应用程序,该应用程序经常使用扩展和写入来读取和写入网络设备。手术通常需要大约7分钟才能完成。。然而,当我同时在两个不同的设备上执行这个应用程序的两个单独的实例时,完成时间延长到15分钟
当我启用 data-search-pseudo-elements 时,它会导致网格内带有图标的行渲染性能降低 100 倍以上。奇怪的是,网格虚拟了行,所以实际上只有 100 行可见。如果没有此设置,渲
我是一名优秀的程序员,十分优秀!