防止ipython将输出存储在Out变量中
问题内容:
我目前正在使用熊猫和ipython。由于在执行pandas数据帧时会对其进行复制,因此每个单元的内存使用量增加了500
mb。我相信这是因为数据存储在Out
变量中,因为默认的python解释器不会发生这种情况。
如何禁用Out
变量?
问题答案:
您的第一个选择是避免产生输出。如果您真的不需要 查看 中间结果,则可以避免它们,并将所有计算结果放在一个单元格中。
如果需要实际显示该数据,可以使用InteractiveShell.cache_size
选项设置缓存的最大大小。将此值设置为0
禁用缓存。
为此,您必须在目录下创建一个名为ipython_config.py
(或ipython_notebook_config.py
)的~/.ipython/profile_default
文件,其内容如下:
c = get_config()
c.InteractiveShell.cache_size = 0
之后,您将看到:
In [1]: 1
Out[1]: 1
In [2]: Out[1]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-2-d74cffe9cfe3> in <module>()
----> 1 Out[1]
KeyError: 1
您还可以使用命令为ipython创建不同的配置文件ipython profile create <name>
。这将在~/.ipython/profile_<name>
默认配置文件下创建一个新的配置文件。然后,您可以使用--profile <name>
加载该配置文件的选项启动ipython 。
另外,您可以使用%reset out
魔术来重置输出缓存或使用%xdel
魔术来删除特定对象:
In [1]: 1
Out[1]: 1
In [2]: 2
Out[2]: 2
In [3]: %reset out
Once deleted, variables cannot be recovered. Proceed (y/[n])? y
Flushing output cache (2 entries)
In [4]: Out[1]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-4-d74cffe9cfe3> in <module>()
----> 1 Out[1]
KeyError: 1
In [5]: 1
Out[5]: 1
In [6]: 2
Out[6]: 2
In [7]: v = Out[5]
In [8]: %xdel v # requires a variable name, so you cannot write %xdel Out[5]
In [9]: Out[5] # xdel removes the value of v from Out and other caches
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-9-573c4eba9654> in <module>()
----> 1 Out[5]
KeyError: 5