【问题标题】:Is the dtype of an ogrid, in numpy, specifiable?在 numpy 中,ogrid 的 dtype 是可指定的吗?
【发布时间】:2017-06-30 04:58:31
【问题描述】:

在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) 之类的替代方案。

【问题讨论】:

    标签: python numpy memory array-broadcasting


    【解决方案1】:

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

    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)]
    

    【讨论】:

      【解决方案2】:

      另一种选择是更直接地使用np.newaxis

      y = np.arange(9000, dtype=np.int16)[:,None]
      x = np.arange(9000, dtype=np.int16)[None,:]
      

      【讨论】:

        猜你喜欢
        • 2014-06-14
        • 1970-01-01
        • 2011-04-13
        • 1970-01-01
        • 2015-06-12
        • 1970-01-01
        • 2014-02-26
        • 2013-08-06
        • 1970-01-01
        相关资源
        最近更新 更多