python - 出于神秘原因,函数为 numpy 数组定义了一个不需要的属性
问题描述
我正在尝试构建一个网格网格以计算插值。我从这个例子中得到启发。我的功能如下:
def oscillatory_(a,b,d,w=w,c=c):
x = np.array([a,b,d])
return np.cos(2*math.pi*w[0,0] + np.sum(c.T*x, axis = 1))
我打电话给:
data = oscillatory_(*np.meshgrid(a,b,d,indexing='ij', sparse=True))
在哪里
a = grid_dim[:,0]
b = grid_dim[:,1]
d = grid_dim[:,2]
只是从 grid_dim 获取的一些值,它是一个 numpy n-array
尝试运行代码时,出现以下错误:
Traceback (most recent call last):
File "/usr/lib/python3.6/code.py", line 91, in runcode
exec(code, self.locals)
File "<input>", line 9, in <module>
File "<input>", line 3, in f
AttributeError: 'numpy.ndarray' object has no attribute 'cos'
我真的不明白他为什么将 cos 分配为属性而不是函数,因为如果我在 *np.meshgrid() 之外运行振荡函数,一切正常。
另外,我玩过下面链接中的玩具示例,添加了一个 np.cos 函数,一切正常。问题出在我的功能上,我不知道在哪里。
我这样做是为了通过以下方式计算插值:
my_interpolating_function = RegularGridInterpolator((a,b,d), data)
对此的任何帮助将不胜感激。非常感谢
解决方案
从稀疏创建一个数组meshgrid
会产生一个对象 dtype 数组
In [448]: I,J=np.meshgrid([0,1,2],[0,1], indexing='ij', sparse=True)
In [449]: I
Out[449]:
array([[0],
[1],
[2]])
In [450]: J
Out[450]: array([[0, 1]])
In [451]: np.array([I, J])
Out[451]:
array([array([[0],
[1],
[2]]), array([[0, 1]])], dtype=object)
使用稀疏 False,您将获得一个有效的数值数组:
In [452]: I,J=np.meshgrid([0,1,2],[0,1], indexing='ij', sparse=False)
In [453]: I
Out[453]:
array([[0, 0],
[1, 1],
[2, 2]])
In [454]: J
Out[454]:
array([[0, 1],
[0, 1],
[0, 1]])
In [455]: np.array([I, J])
Out[455]:
array([[[0, 0],
[1, 1],
[2, 2]],
[[0, 1],
[0, 1],
[0, 1]]])
推荐阅读
- parsing - Boost Spirit X3 支持左递归吗?
- python - 如何通过 Python 中的 LXML 引用父元素并删除 RSS XML 中的父元素?
- javascript - 在 Click 函数中访问“this”
- javascript - 使用带有 Materialize v1.0.0 的 React.JS 无法初始化 JS
- php - 条纹电子邮件收据项目
- java - “selection”和“selectionArgs”子句如何为 ContentProvider 工作
- tfs - 使 release def 上下文菜单项有条件地不可见
- java - Java - PDF 转 PCL
- spring-boot - 使用 spring-boot 2.0.2.RELEASE 并且 FlyWay 没有运行。没有错误
- javascript - 媒体查询 - 当我调整窗口大小时,响应式侧边菜单出现并迅速消失