python - numpy 中 ogrid 的 dtype 是否可以指定?

标签 python numpy memory array-broadcasting

在Python的numpy中,为什么ogrid总是产生int64结果?

对于我的应用程序,由于内存限制(当输出组件稍后一起广播时会发挥作用),我不想使用 int64。有没有比事后重铸更好的选择:

y, x = np.ogrid[:9000,:9000]
y = y.astype(np.int16)
x = x.astype(np.int16)

对于大多数其他 numpy 调用,更简洁的解决方案是使用 dtype=... 可选参数,但 ogrid 不会作为函数调用。相反,它似乎与像 a+b 这样的运算符相当,只不过它们通常有像 np.add(a,b,dtype=np.int8) 这样的替代选项。

最佳答案

您可以使用ix_生成相同的形状,并完全控制数据类型:

In [476]: np.ix_(np.arange(5,dtype=float),np.arange(5,dtype=np.int16))
Out[476]: 
(array([[ 0.],
        [ 1.],
        [ 2.],
        [ 3.],
        [ 4.]]), array([[0, 1, 2, 3, 4]], dtype=int16))
In [477]: np.ogrid[:5,:5]
Out[477]: 
[array([[0],
        [1],
        [2],
        [3],
        [4]]), array([[0, 1, 2, 3, 4]])]

meshgrid 以及:

In [488]: np.meshgrid(np.arange(5, dtype=float), np.arange(5, dtype=np.int16), sparse=True, indexing='ij')
Out[488]: 
[array([[ 0.],
        [ 1.],
        [ 2.],
        [ 3.],
        [ 4.]]), array([[0, 1, 2, 3, 4]], dtype=int16)]

关于python - numpy 中 ogrid 的 dtype 是否可以指定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44838864/

相关文章:

android - View 引用成员变量和局部变量的区别

python - s.replace string方法,循环遍历字符串

python - pyspark boolean 配置与大写有关的问题

jquery - 未使用 jquery 将数据发送到 Django View

python - 将关心索引的函数应用于 numpy 数组的每个元素

python-3.x - 为什么在使用 numpy 1.13.3 时从 scipy 导入 'comb' 会失败?

c - 如何在c中打印内存位

python - 如何使用 pandas 在 ndarray 上创建索引

python - Numpy:查找范围内元素的索引

c - 需要一种优化堆使用的方法 C - Freebsd/glibc