Pandas GroupBy内存释放

2024-04-16 19:23:55 发布

您现在位置:Python中文网/ 问答频道 /正文

问题

我注意到,迭代PandasGroupBy对象时分配的内存在迭代后没有释放。我使用resource.getrusage(resource.RUSAGE_SELF).ru_maxrsssecond answer in this post for details)来测量Python进程使用的活动内存总量。在

import resource
import gc

import pandas as pd
import numpy as np

i = np.random.choice(list(range(100)), 4000)
cols = list(range(int(2e4)))

df = pd.DataFrame(1, index=i, columns=cols)

gb = df.groupby(level=0)
# gb = list(gb)
for i in range(3):
    print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6)
    for idx, x in enumerate(gb):
        if idx == 0:
            print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6)
    # del idx, x
    # gc.collect()

打印以下总活动内存(gb)

^{pr2}$

解决方案

取消注释del idx, xgc.collect()可解决此问题。但是,我必须del所有引用通过迭代groupby返回的数据帧的变量(这可能会很麻烦,这取决于内部for循环中的代码)。新的打印内存使用变成:

0.671768
1.297412
1.297992
1.297992
1.297992
1.297992

或者我可以取消注释gb = list(gb)。由此产生的内存使用量与以前的解决方案大致相同:

1.32874
1.32874
1.32874
1.32874
1.32874
1.32874

问题

  1. 为什么通过groupby迭代产生的数据帧内存在迭代完成后没有释放?在
  2. 有没有比上述两个更好的解决方案?如果不是,这两个解决方案中哪一个“更好”?在

Tags: 内存inimportselfforru解决方案gc
2条回答

记忆怪异

这很有趣!您不需要del idx, x。只有使用gc.collect()才使内存保持不变。这比在循环中包含del语句要干净得多。在

Why is memory for DataFrames resulting from iteration through the groupby not deallocated after iteration is completed?

在你的代码中没有你del对象gb,这意味着在最后它仍然存在。一件事是让一个迭代器到达其循环的末尾,然后我希望它自动消亡,但是产生迭代器的对象仍然存在,以防您需要做其他事情(再次迭代、聚合等)。在

相关问题 更多 >