【问题标题】:setting type of numpy structure array设置numpy结构数组的类型
【发布时间】:2018-12-19 06:22:43
【问题描述】:

我有一个 numpy 结构化数组,我需要在其中控制各个元素的数据类型。

这是我的例子:

y = array([(True, 144.0), 
           (True, 86.0), 
           (True, 448.0), 
           (True, 76.0), 
           (True, 511.0)], dtype=object)

如果我这样做:

print(y.dtype.fields)

我回来了:

None

但是,我想要的是“bool”和“float”。 如果我访问单个元素,例如 y[0][0]y[0][1],我肯定会看到它们确实是 bool 和 float。
我对此感到非常困惑。有什么想法吗?

我需要这个,因为我使用包“sciki-survival gradient boosting”:https://scikit-survival.readthedocs.io/en/latest/generated/sksurv.ensemble.GradientBoostingSurvivalAnalysis.html#sksurv.ensemble.GradientBoostingSurvivalAnalysis.fit 输入需要是“bool”和“float”类型的结构化数组。

【问题讨论】:

  • y.dtype 给你什么?
  • 它给出dtype('O'),即np.object_。这不是结构化数组
  • @Eric 如何构建结构化数组,然后使用相同的内容?
  • 你是如何构建这个数组的?
  • @KimO,看起来您正在使用wrong answer 中的previous question(或者没有阅读我对该答案的评论)。一次迈出一步。了解您进行的每一步。这将帮助您更快地解决问题。

标签: python numpy


【解决方案1】:

初始化结构化数组时,请确保指定数据类型。

例如:

y = np.array([(True, 144.0), (True, 86.0), (True, 448.0)],
          dtype=[('col_1', 'bool'), ('col_2', 'f4')])

这应该有效并且:

y.dtype.fields 

根据需要显示:

mappingproxy({'col_1': (dtype('bool'), 0), 'col_2': (dtype('float32'), 1)})

在此处查看文档:https://docs.scipy.org/doc/numpy/user/basics.rec.html

【讨论】:

    【解决方案2】:

    我有一个 numpy 结构化数组

    不,你没有:

    np.array(..., dtype=object)

    你有一个 numpy 对象数组,其中包含元组。

    您可以使用y.astype([('b', bool), ('f', float)])将其转换为结构化数组

    【讨论】:

      【解决方案3】:

      要创建结构化数组,您必须事先指定数据类型。如果你只是使用numpy.array 和一个list-literal 对,那么你会得到一个带有对象dtype 的数组。因此,您需要执行以下操作:

      >>> mytype = np.dtype([('b', bool), ('f',float)])
      >>> mytype
      dtype([('b', '?'), ('f', '<f8')])
      

      然后将mytype传递给数组构造函数:

      >>> structured = np.array(
      ...    [(True, 144.0), (True, 86.0),
      ...     (True, 448.0), (True, 76.0),
      ...     (True, 511.0), (True, 393.0), 
      ...     (False, 466.0), (False, 470.0)], dtype=mytype)
      >>>
      >>> structured
      array([( True,  144.), ( True,   86.), ( True,  448.), ( True,   76.),
             ( True,  511.), ( True,  393.), (False,  466.), (False,  470.)],
            dtype=[('b', '?'), ('f', '<f8')])
      

      【讨论】:

        猜你喜欢
        • 2013-09-02
        • 1970-01-01
        • 1970-01-01
        • 2020-12-17
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 2014-11-10
        • 1970-01-01
        相关资源
        最近更新 更多