[英]Python Pandas - groupby() with apply() & rolling() very slow
[英]Pandas - very slow when using groupby() with rolling() and apply()
在 Pandas 中为大型数据帧(1500682 行)调用 groupby 以及滚动和应用函数时,我的性能非常慢。 我试图获得具有不同权重的滚动移动平均线。
运行缓慢的代码部分是:
df['rolling'] = df.groupby('i2')['x'].rolling(3).apply(lambda x: x[-3]*0.1+x[-2]*0.9).reset_index(level=0, drop=True).reindex(df.index)
完整的代码(带有数据)是:
import pandas as pd
from random import randint
# data (it takes some time to create [less than 1 minute in my computer])
data1 = [[[[randint(0, 100) for i in range(randint(1, 2))] for i in range(randint(1, 3))] for i in range(5000)] for i in range(100)]
data2 = pd.DataFrame(
[
(i1, i2, i3, i4, x4)
for (i1, x1) in enumerate(data1)
for (i2, x2) in enumerate(x1)
for (i3, x3) in enumerate(x2)
for (i4, x4) in enumerate(x3)
],
columns = ['i1', 'i2', 'i3', 'i4', 'x']
)
data2.drop(['i3', 'i4'], axis=1, inplace = True)
df = data2.set_index(['i1', 'i2']).sort_index()
## conflicting part of the code ##
df['rolling'] = df.groupby('i2')['x'].rolling(3).apply(lambda x: x[-3]*0.1+x[-2]*0.9).reset_index(level=0, drop=True).reindex(df.index)
如果您能详细说明代码以使其更高效且执行速度更快,我将不胜感激。
如果我理解正确,您可以尝试:
grp=df.groupby('i2')['x']
df['rolling']=grp.shift(2).mul(0.1).add(grp.shift(1).mul(0.9))
现在详细说明:
为什么不.apply(...)
:
我什么时候应该在我的代码中使用 pandas apply() ?
你应该做的是使用任何利用矢量化操作的东西。 我在这里做了一些更详细的解释:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.