从 Python 中的对象中提取数组

Extract array from object in Python

我有一个名为 mesh 的变量,类型为 object,是从 MATLAB .mat 文件中提取的。 (编辑:下面的可重现示例)

In [1]: mesh
Out[1]: 
array([[ array([[ (array([[ 89, 108]], dtype=uint8), 
         array([[-131.659809],
          [-131.659809],
          [-131.659809],
          ..., 
          [  52.022239],
          [  52.022239],
          [  52.022239]]), 
         array([[ 189.358345],
          [ 187.271049],
          [ 185.183753],
          ..., 
          [ -29.807736],
          [ -31.895032],
          [ -33.982328]]))]],
         dtype=[('dim', 'O'), ('x', 'O'), ('y', 'O')])]], dtype=object)

如何访问各个数组 dimxy

可重现的例子:

我无法将 dtype=uint8 分配给导入对象中的数组。

此外,导入对象的对象大小为 (1,1),而此示例的对象大小为 (1,1,1,1)。

import numpy as np

mesh = np.array([[ np.array([[ (np.array([[ 6, 6]], dtype=float), 
     np.array([[-131.659809],
      [-131.659809],
      [-131.659809], 
      [  52.022239],
      [  52.022239],
      [  52.022239]]), 
     np.array([[ 189.358345],
      [ 187.271049],
      [ 185.183753],
      [ -29.807736],
      [ -31.895032],
      [ -33.982328]]))]],
     dtype=[('dim', 'O'), ('x', 'O'), ('y', 'O')])]], dtype=object)

要访问上面的单独数组,可以执行以下操作:

>>> mesh[0][0][0][0][0] # dim
array([[ 6.,  6.]])
>>> mesh[0][0][0][0][1] # x
array([[-131.659809],
   [-131.659809],
   [-131.659809],
   [  52.022239],
   [  52.022239],
   [  52.022239]])
>>> mesh[0][0][0][0][2] # y
array([[ 189.358345],
   [ 187.271049],
   [ 185.183753],
   [ -29.807736],
   [ -31.895032],
   [ -33.982328]])

要设置一个值,例如可以这样做:

>>> mesh[0][0][0][0][0][0][0]=1    
>>> mesh
array([[[[ (array([[ 1.,  6.]]), array([[-131.659809],
   [-131.659809],
   [-131.659809],
   [  52.022239],
   [  52.022239],
   [  52.022239]]), array([[ 189.358345],
   [ 187.271049],
   [ 185.183753],
   [ -29.807736],
   [ -31.895032],
   [ -33.982328]]))]]]], dtype=object)

免责声明

这个答案是 hack,不是解决方案。它并不意味着被解释为一般答案,而是特定于上面的确切示例。它不处理 numpy,只是能够访问特定的数组。