In [206]: a
Out[206]:
array([( 0., 1., 2.), (10., 11., 12.)],
dtype=[('PositionX', '<f8'), ('PositionY', '<f8'), ('PositionZ', '<f8')])
記錄是一個複合numpy的D類對象,即顯示爲一個元組。
In [207]: type(a[0])
Out[207]: numpy.void
In [208]: a[0].dtype
Out[208]: dtype([('PositionX', '<f8'), ('PositionY', '<f8'), ('PositionZ', '<f8')])
字段陣列的(「列」)是數組,然後執行正常陣列數學。
In [209]: a['PositionX']
Out[209]: array([ 0., 10.])
In [210]: a['PositionX']+a['PositionY']
Out[210]: array([ 1., 21.])
但是,數學尚未爲複合D型定義:
In [211]: a[0]+a[1]
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype([('PositionX', '<f8'), ('PositionY', '<f8'), ('PositionZ', '<f8')]) ....
如果你讓我轉換整個數組到2d,我可以添加行:
In [213]: a1=np.array(a.tolist())
In [214]: a1
Out[214]:
array([[ 0., 1., 2.],
[ 10., 11., 12.]])
In [215]: a1[0]+a1[1]
Out[215]: array([ 10., 12., 14.])
有是將結構化數組轉換爲2d的其他方式(使用view
或astype
),但此tolist()
最易於使用且最一致。更多信息請登錄https://stackoverflow.com/a/43380941/901925
但是要對單個記錄進行數學運算,您必須將它們轉換爲數組或像顯示的元組一樣對待它們。
In [218]: np.array(a[0].tolist())
Out[218]: array([ 0., 1., 2.])
In [219]: np.array(a[0].tolist())+np.array(a[1].tolist())
Out[219]: array([ 10., 12., 14.])
但是你對這個數組感到滿意嗎,還是你想要回到a.dtype
?
In [234]: np.array(tuple(asum), a.dtype)
Out[234]:
array((10., 12., 14.),
dtype=[('PositionX', '<f8'), ('PositionY', '<f8'), ('PositionZ', '<f8')])
數據結構化數組必須在元組或元組列表中。
你,如果你使用壓縮的辦法,@Mohamed Lakhal
顯示
In [236]: [i+j for i,j in zip(a[0],a[1])]
Out[236]: [10.0, 12.0, 14.0]
In [237]: np.array(tuple([i+j for i,j in zip(a[0],a[1])]), a.dtype)
雖然view
方法,因爲Divakar評論整個數組轉換做同樣的dtype
轉換:
In [227]: a.view('<f8')
Out[227]: array([ 0., 1., 2., 10., 11., 12.])
In [228]: a.view('<f8').reshape(-1,3)
Out[228]:
array([[ 0., 1., 2.],
[ 10., 11., 12.]])
它不起作用:
In [229]: a[0].view('<f8')
....
ValueError: new type not compatible with array.
這是一個更好的轉換器,二維數組:
In [239]: a.view('3f8')
Out[239]:
array([[ 0., 1., 2.],
[ 10., 11., 12.]])
In [240]: a[0].view('3f8')
Out[240]: array([ 0., 1., 2.])
In [241]: a[[0,1]].view('3f8')
Out[241]:
array([[ 0., 1., 2.],
[ 10., 11., 12.]])
In [242]: a[[0,1]].view('3f8').sum(axis=0)
Out[242]: array([ 10., 12., 14.])
你嘗試從這個職位的建議 - http://stackoverflow.com/questions/5957380/convert-structured-array-正常的numpy數組?基本上:'a.view(np.float64).reshape(len(a), - 1).sum(0)'。 – Divakar