问题
我注意到,在迭代Pandas的GroupBy对象时分配的内存在迭代后没有被释放。我使用resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
(有关详细信息,请参见此帖子的第二个答案)来测量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为单位)
0.671732
1.297424
1.297952
1.923288
1.923288
2.548624
解决方案
取消注释del idx, x
和gc.collect()
可以解决问题。但是,我必须del
所有引用通过对groupby进行迭代返回的DataFrames的变量(这取决于内部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
问题
- 为什么通过对groupby进行迭代后生成的DataFrame内存没有在迭代完成后被释放?
- 除了上述两种解决方案,是否有更好的解决方案?如果没有,这两种解决方案中哪一种更好?