Python 错误名称错误:未定义名称“np”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52921955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error NameError: name 'np' is not defined
提问by Piistasyo
from numpy import *
x = np.random.randint(low=10, high=30, size=6)
print(x)
"C:\Users\Piistasyo\PycharmProjects\test project\venv\Scripts\python.exe" "C:/Users/Piistasyo/PycharmProjects/test project/loop.py"
Traceback (most recent call last):
File "C:/Users/Piistasyo/PycharmProjects/test project/loop.py", line 44, in <module>
x = np.random.randint(low=10, high=30, size=6)
NameError: name 'np' is not defined
why am i getting this error? pls help i already installed the numpy package
为什么我收到这个错误?请帮助我已经安装了 numpy 包
回答by U10-Forward
As @aydow says, "change from numpy import *
to import numpy as np
":
正如@aydow 所说,“更改from numpy import *
为import numpy as np
”:
import numpy as np
...
Or don't write np
:
或者不写np
:
from numpy import *
x = random.randint(low=10, high=30, size=6)
...
Because, from numpy import *
, Import every function in numpy, so np
is not a function of numpy, so have to Import numpy like import numpy as np
, Or, Remove np
part of np.random.randint(low=10, high=30, size=6)
, and make it like this: random.randint(low=10, high=30, size=6)
, it's all since random
is a function of numpy, basically that's all, to explain
因为,from numpy import *
, 导入 numpy 中的每个函数,所以np
不是 numpy 的函数,所以必须导入 numpy 之类的import numpy as np
, 或者,删除np
一部分np.random.randint(low=10, high=30, size=6)
,并使其像这样:random.randint(low=10, high=30, size=6)
,这都是因为random
是 numpy 的函数,基本上就是这样,解释
回答by Green Cloak Guy
You haven't defined np
.
你还没有定义np
.
The first thing you're currently doing is
您目前正在做的第一件事是
from numpy import *
This imports the package numpy
, and everything inside of that package. However, numpy does not contain a module called np
. The typical practice for numpy is to insteaddo
这将导入 packagenumpy
以及该包中的所有内容。但是,numpy 不包含名为np
. 为numpy的典型做法是不是做
import numpy as np
This imports justthe package numpy
, and renames it to np
so that you can dereference it by using the dot operator on np
. This allows you to call np.random()
, since random
is a member of numpy
, which is aliased to np
.
这仅导入包numpy
,并将其重命名为 ,np
以便您可以使用点运算符 on 取消引用它np
。这允许您调用np.random()
,因为random
是 的成员numpy
,别名为np
。
With what you're currently doing, you could do either numpy.random()
or just random
(since it was part of the *
that you imported from numpy).
对于您目前正在做的事情,您可以做numpy.random()
或只做random
(因为它是*
您从 numpy 导入的一部分)。