【问题标题】:IPYTHON code using numpy arrays and %pylab inline使用 numpy 数组和 %pylab 内联的 IPYTHON 代码
【发布时间】:2015-03-27 05:01:17
【问题描述】:

我为IPython Notebook 编写了代码。顶部显示%pylab inline。 代码使用numpy 和np。我正在尝试在PyCharm 中使用此代码创建一个项目,但它无法运行。我将 import numpy 放在顶部,但使用 np 的行失败。上面写着global name 'np' not defined。

我确定%pylab inline 行与它有关。有没有我可以使用的导入来定义np 还是这只是IPython 的东西?

【问题讨论】:

    标签: python numpy ipython


    【解决方案1】:

    将代码从IPython 传输到PyCharm 时, 将%pylab inline 替换为以下代码:

    import numpy
    import matplotlib
    from matplotlib import pylab, mlab, pyplot
    np = numpy
    plt = pyplot
    
    from IPython.core.pylabtools import figsize, getfigs
    
    from pylab import *
    from numpy import *
    

    【讨论】:

      【解决方案2】:

      是的,使用import numpy as np 而不是import numpy。

      使用前缀numpy 可能非常麻烦。因此,numpy 模块通常以较短的模块名称 np 导入。

      这两个代码sn-ps的作用是一样的:

      import numpy
      numpy.sqrt(3*3 + 4*4)
      

      这里是别名:

      import numpy as np
      np.sqrt(3*3 + 4*4)
      

      对于较大的程序,别名版本更简洁,因此 import numpy as np 现在可以被视为标准。

      【讨论】:

      • 忘了提我已经尝试过了,我的程序在 PyCharm 中崩溃了。所以在我看来 np 的工作方式与 numpy 不同? %pylab inline 做什么? IPython 代码同时使用 "numpy" 和 "np" 。在 PyCharm 中,当我将 np 引用更改为 numpy 时,反之亦然,它会崩溃。为什么要这样做?
      • %pylab 为内联图形选择必要的后端,并为您执行大量导入。请注意,它现在已被弃用。也就是说,在不知道看到笔记本的情况下,我只能猜测这里有什么问题。
      猜你喜欢
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多