我是Numpy的ndarray类的子类,添加了一些元数据和其他方法.我试图按照指示这篇文章和那一个.但是,一些Numpy(或Scipy)函数返回基类"ndarray"而不是我的自定义子类.其他Numpy函数返回我的子类,我不知道差异的原因是什么.如何让所有numpy/scipy函数返回我的子类?这就是我做的:
class Signal(np.ndarray):
def __new__(cls, filename):
#print "In __new__" #TEMP DEBUG
ret = np.fromfile(filename, dtype = np.int32)
ret = ret.view(cls) # convert to my class, i.e. Signal
ret.parse_filename(filename)
return ret
def __array_finalize__(self, obj):
#print "in __array_finalize__" #TEMP DEBUG
if obj is None: return # shouldn't actually happen.
# copy meta-fields from source, if it has them (otherwise put None's)
self.filename = getattr(obj, "filename", None)
self.folder = getattr(obj, "folder", None)
self.label = getattr(obj, "label", None)
self.date = …Run Code Online (Sandbox Code Playgroud) 注意:我检查了重复,没有明确回答我的问题.如果我错过了什么,我相信你会告诉我的!
为了清理我的代码,我一直在寻找在我的程序中导入SciPy和NumPy的标准约定.我知道没有严格的准则,我可以按照我想要的方式去做,但有时候,我仍然会发现矛盾的指示.
例如,我在某处读过NumPy只是为了实现数组对象,而SciPy则用于其他所有科学算法.所以NumPy应该用于数组操作而SciPy用于其他所有东西......另一方面,SciPy在其主命名空间中导入每个Numpy函数,这scipy.array()与numpy.array()(看这个问题)相同,所以NumPy只能用于当没有使用SciPy时,因为它们是重复的......
使用SciPy和NumPy的推荐方法是什么?作为一名科学家,sqrt(-1)应该返回一个复杂的数字,所以我倾向于只使用SciPy.
现在,我的代码开头是:
import numpy as np
from scipy import *
from matplotlib import pyplot as plt
Run Code Online (Sandbox Code Playgroud)
我使用scipy进行数学运算(例如log10())和numpy进行数组创建/运算(例如np.zeros()).用SciPy一路走下去并且永远不会明确导入NumPy会不会很好?未来的更新会从SciPy中删除NumPy的数组操作吗?
我有一个代码库,我正在清理前一个开发人员的一些混乱的决定.通常,他做过类似的事情:
from scipy import *
from numpy import *
Run Code Online (Sandbox Code Playgroud)
...当然,这会污染名称空间,并且很难分辨出模块中的属性最初来自何处.
有没有办法让Python分析并为我解决这个问题?有没有人为此做过一个实用程序?如果没有,这样的实用程序怎么可能?
我是第一次进入SciPy LinAlg模块,并且看到了以下功能:
def _makearray(a):
new = asarray(a)
wrap = getattr(a, "__array_prepare__", new.__array_wrap__)
return new, wrap
Run Code Online (Sandbox Code Playgroud)
到底是__array_wrap__做什么的?我找到了文档,但是我不明白这个解释:
At the end of every ufunc, this method is called on the input object with the
highest array priority, or the output object if one was specified. The ufunc-
computed array is passed in and whatever is returned is passed to the user.
Subclasses inherit a default implementation of this method, which transforms the
array into a new instance …Run Code Online (Sandbox Code Playgroud) 可能重复:
scipy和numpy之间的关系
例如,NumPy的具有窗口功能 bartlett,blackman,hamming,hanning,kaiser,而SciPy的拥有这些还有几个,但他们似乎产生相同的输出.
NumPy有numpy.fft.fft2(a, s=None, axes=(-2, -1)).
SciPy有scipy.fftpack.fft2(x, shape=None, axes=(-2, -1), overwrite_x=0).
为什么有重复?只是为了向后兼容?如果是这样,为什么他们在不同的地方定义不同?在写新东西时我应该更喜欢哪一个?
我知道numpy和scipy都具有polyfit功能,并在这里访问过:http ://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html
为什么scipy.org上有一个有关numpy.polyfit的页面?numpy.polyfit和scipy.polyfit是否相同?如果没有,我应该使用哪一个?