python - 将网格网格作为参数传递,将数组作为另一个参数
问题描述
我似乎记得看到可以将 numpy 网格网格作为参数与数组一起传递给函数,并让函数在迭代网格网格的元素时保持数组的完整性。我梦到这个还是有人知道我指的是什么?我搜索了 SOF、google 和 numpy 文档,但没有成功。
例子:
def makeGridandArray(i=60, j=40, ratio=10):
arr = np.arange(i*j).reshape(i, j)
x,y = np.meshgrid(np.arange(0, i, ratio), np.arange(0, j, ratio), sparse=True)
return crop(x, y, ratio, arr)
def crop(x, y, ratio, Arr):
return np.average(Arr[x:x+ratio, y:y+ratio])
上面的代码将抛出一个无效切片错误,因为 Arr 正在与网格网格一起迭代。
>>> x=makeGridandArray()
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/private/var/mobile/Containers/Shared/AppGroup/A181F23F-E674-4B44-882C-B03A93E0E84A/Pythonista3/Documents/so.py", line 752, in makeGridandArray
return crop(x,y, ratio, arr)
File "/private/var/mobile/Containers/Shared/AppGroup/A181F23F-E674-4B44-882C-B03A93E0E84A/Pythonista3/Documents/so.py", line 755, in crop
return np.average(Arr[x:x+ratio, y:y+ratio])
IndexError: invalid slice
在上面的示例中,我希望返回一个 6x4 数组,其中包含 Arr 的每个 10x10 子集的平均值。我意识到这可以通过 np.average 和重塑来实现,但我正在寻找的是如何将 Arr 整体传递给函数的语法,同时利用将网格网格传递给函数。谢谢!
解决方案
meshgrid
is just a way of generating two arrays that can index and broadcast together. For example:
In [302]: x,y=np.meshgrid([1,2,3],[4,5,6],sparse=True)
In [303]: x
Out[303]: array([[1, 2, 3]])
In [304]: y
Out[304]:
array([[4],
[5],
[6]])
One is (1,3) shape, the other (3,1); together the produce a (3,3) result
With addition (or other binary math):
In [305]: x+y
Out[305]:
array([[5, 6, 7],
[6, 7, 8],
[7, 8, 9]])
As indices in a 2d array:
In [306]: arr = np.arange(1,101).reshape(10,10)
In [307]: arr[x,y]
Out[307]:
array([[15, 25, 35],
[16, 26, 36],
[17, 27, 37]])
An array cannot be used as a slice endpoint:
In [310]: np.arange(10)[x: x+3]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-310-adcd5e98b614> in <module>
----> 1 np.arange(10)[x: x+3]
TypeError: only integer scalar arrays can be converted to a scalar index
Just because an array is generated by meshgrid
, it doesn't mean it has special properties, or be used in ways that any other array can't.
推荐阅读
- c - C 输入值从 .txt 到 struct
- python - 如何在包中运行脚本
- javascript - 使用jQuery检测是否将鼠标悬停在div中的图像上
- macos - SwiftUI 列表项 - 单击时更改颜色
- python - Flask 错误:在服务器上找不到请求的 URL。如果您手动输入了 URL,请检查您的拼写并重试
- terraform - 如果是创建的,如何使用terraform在inventory.ini.tmpl中写入虚拟机的名称和ip?
- javascript - Redux坚持黑名单删除reducer?
- javascript - JavaScript 自动填充问题
- python-3.x - 有人可以解释一下为什么 plyer filechooser 在我的 android 设备上不起作用吗?
- python - Tensorflow-GPU 不使用带有 CUDA、CUDNN 的 GPU