如何在 numpy 中声明类似于此 C 结构的结构化数组类型?



我有以下c结构:

typedef struct
{
int blah[10];
} mine;

如何为此声明结构化的 numpy 数组 dtype?

我试过了:

mine_dtype = [
('blah', [np.int32])
]

但这行不通。

谢谢。

In [267]: mine_dtype = [ 
...:             ('blah', [np.int32]) 
...:         ]                                                                              
In [268]: np.dtype(mine_dtype)                                                                   
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-268-6f0bb6a0df45> in <module>
----> 1 np.dtype(mine_dtype)
TypeError: data type not understood
In [269]: mine_dtype = [ 
...:             ('blah', np.int32) 
...:         ]                                                                              
In [270]: np.dtype(mine_dtype)                                                                   
Out[270]: dtype([('blah', '<i4')])
In [271]: np.ones(3, dtype=mine_dtype)                                                           
Out[271]: array([(1,), (1,), (1,)], dtype=[('blah', '<i4')])
In [272]: _['blah']                                                                              
Out[272]: array([1, 1, 1], dtype=int32)

展开 dtype 以为每个字段指定 10 个元素:

In [282]: mine_dtype = [ 
...:             ('blah', np.int32, 10) 
...:         ]                                                                              
In [283]: arr = np.zeros(3,mine_dtype)                                                           
In [284]: arr                                                                                    
Out[284]: 
array([([0, 0, 0, 0, 0, 0, 0, 0, 0, 0],),
([0, 0, 0, 0, 0, 0, 0, 0, 0, 0],),
([0, 0, 0, 0, 0, 0, 0, 0, 0, 0],)], dtype=[('blah', '<i4', (10,))])
In [285]: arr['blah'][:]=np.arange(10)                                                           
In [286]: arr                                                                                    
Out[286]: 
array([([0, 1, 2, 3, 4, 5, 6, 7, 8, 9],),
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9],),
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9],)], dtype=[('blah', '<i4', (10,))])

最新更新