SciPy/NumPy导入指南 [英] SciPy/NumPy import guideline
问题描述
注意:我检查了重复项,但没有清楚的答案.我相信您会告诉我如果我错过了什么!
Notice: I checked for duplicate and nothing clearly answers my question. I trust you'll let me know if I missed something!
为了清理代码,我一直在寻找在程序中导入SciPy和NumPy的标准约定.我知道没有严格的指导方针,我可以按照自己想要的方式来做,但是有时我仍然会发现矛盾的指示.
In an effort to clean up my code, I have been looking for a standard convention for importing SciPy and NumPy in my programs. I know there is no strict guideline and I can do it the way I want, but from time to time, I still find contradictory instructions.
例如,我在某处读到NumPy仅用于实现数组对象,而SciPy用于其他所有科学算法.因此,应将NumPy用于数组操作,将SciPy用于其他所有操作...
另一方面,SciPy会在其主命名空间中导入每个Numpy函数,以使scipy.array()
与numpy.array()
相同(
For example, I've read somewhere that NumPy is meant to only implement the array object, while SciPy is there for every other scientific algorithms. So NumPy should be used for array operation and SciPy for everything else...
On the other hand, SciPy imports every Numpy functions in its main namespace, such that scipy.array()
is the same thing as numpy.array()
(see this question), so NumPy should only be used when SciPy is not being used, as they are duplicates...
与SciPy和NumPy一起使用的推荐方法是什么?作为科学家,sqrt(-1)
应该返回一个复数,所以我倾向于只使用SciPy.
What is the recommended way to work with SciPy and NumPy? Being a scientist, sqrt(-1)
should return a complex number, so I'm inclined to go with SciPy only.
现在,我的代码开始于:
Right now, my code starts with:
import numpy as np
from scipy import *
from matplotlib import pyplot as plt
我将scipy用于数学运算(例如log10()
),将numpy用于数组创建/运算(例如np.zeros()
).一路使用SciPy且永远不要显式导入NumPy会很好吗?将来的更新是否会从SciPy中删除NumPy的数组操作?
I use scipy for mathematical operation (such as log10()
) and numpy for array creation/operations (such as np.zeros()
). Would it be fine to go all the way with SciPy and never import NumPy explicitly? Will a future update remove NumPy's array manipulation from SciPy?
推荐答案
我建议您做类似的事情
import numpy as np
import scipy as sp
相反. from ... import *
总是很危险的,尤其是对于大型模块,例如numpy
和scipy
.以下说明了原因:
instead. It is always dangerous to do from ... import *
especially with large modules such as numpy
and scipy
. The following illustrates why:
>>> any(['foo'])
True
>>> from scipy import *
>>> any(['foo'])
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
any(['foo'])
File "C:\Python27\lib\site-packages\numpy\core\fromnumeric.py", line 1575, in any
return _wrapit(a, 'any', axis, out)
File "C:\Python27\lib\site-packages\numpy\core\fromnumeric.py", line 37, in _wrapit
result = getattr(asarray(obj),method)(*args, **kwds)
TypeError: cannot perform reduce with flexible type
这是怎么回事?标准的python内置函数any
被具有不同行为的scipy.any
代替.这可能会破坏任何使用标准any
的代码.
What happens here? The standard python builtin function any
is replaced by scipy.any
which has different behavior. That might break any code that uses the standard any
.
这篇关于SciPy/NumPy导入指南的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!