【问题标题】:Numpy object array of numerical arrays数值数组的numpy对象数组
【发布时间】:2010-07-17 19:55:55
【问题描述】:

我想用dtype=np.object 创建一个数组,其中每个元素都是一个数值类型的数组,例如 int 或 float。例如:

>>> a = np.array([1,2,3])
>>> b = np.empty(3,dtype=np.object)
>>> b[0] = a
>>> b[1] = a
>>> b[2] = a

创建我想要的:

>>> print b.dtype
object

>>> print b.shape
(3,)

>>> print b[0].dtype
int64

但我想知道是否没有办法将第 3 行到第 6 行写入一行(特别是因为我可能想要连接 100 个数组)。我试过了

>>> b = np.array([a,a,a],dtype=np.object)

但这实际上将所有元素转换为 np.object:

>>> print b.dtype
object

>>> print b.shape
(3,)

>>> print b[0].dtype
object

有人知道如何避免这种情况吗?

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    它并不完全漂亮,但是......

    import numpy as np
    
    a = np.array([1,2,3])
    b = np.array([None, a, a, a])[1:]
    
    print b.dtype, b[0].dtype, b[1].dtype
    # object int32 int32
    

    【讨论】:

      【解决方案2】:
      a = np.array([1,2,3])
      b = np.empty(3, dtype='O')
      b[:] = [a] * 3
      

      应该够了。

      【讨论】:

        【解决方案3】:

        我找不到任何优雅的解决方案,但至少手动完成所有事情的更通用解决方案是声明表单的函数:

        def object_array(*args):
            array = np.empty(len(args), dtype=np.object)
            for i in range(len(args)):
                array[i] = args[i]
            return array
        

        我可以这样做:

        a = np.array([1,2,3])
        b = object_array(a,a,a)
        

        然后我得到:

        >>> a = np.array([1,2,3])
        >>> b = object_array(a,a,a)
        >>> print b.dtype
        object
        >>> print b.shape
        (3,)
        >>> print b[0].dtype
        int64
        

        【讨论】:

          【解决方案4】:

          我认为 anyarray 是你需要的:

          b = np.asanyarray([a,a,a])
          >>> b[0].dtype
          dtype('int32')
          

          不确定其他 32 位整数发生了什么。

          不确定它是否有帮助,但如果你添加另一个不同形状的数组,它会转换回你想要的类型:

          import numpy as np
          a = np.array([1,2,3])
          b = np.array([1,2,3,4])
          b = np.asarray([a,b,a], dtype=np.object)
          print(b.dtype)
          >>> object
          print(b[0].dtype)
          >>> int32
          

          【讨论】:

          • 那一定是我的python运行在32位。
          • 这似乎不起作用,因为 b.dtype 的类型是 np.int64,而不是 np.object。
          猜你喜欢
          • 1970-01-01
          • 2022-01-26
          • 2020-12-16
          • 2011-06-20
          • 1970-01-01
          • 1970-01-01
          • 2011-09-02
          • 1970-01-01
          • 2015-05-05
          相关资源
          最近更新 更多