问题
我注意到在遍历 Pandas 时分配了内存 GroupBy迭代后对象不会被释放。我使用 resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
( second 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 为单位)
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 迭代产生的 DataFrames 的内存没有被释放?
- 有没有比以上两个更好的解决方案?如果不是,这两种解决方案中哪一种“更好”?
最佳答案
内存怪异
这非常有趣!您不需要 del idx, x
。只有使用 gc.collect()
才能为我保持内存不变。这比在循环中包含 del
语句要干净得多。
关于python - Pandas GroupBy 内存释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35782929/