Numpy 系列(九)- 結構化數組

  簡介 

以前咱們操做Numpy的數組時,都是經過索引來操做的。針對二維數組,使用索引能夠完成對行、列的操做。可是這是很是不直觀的。能夠把二維數組想象成一個excel表格,若是表格沒有列名,操做起來會很是麻煩,針對這種狀況,Numpy提供告終構化數組用來操做每列數據。python

以前咱們操做Numpy的數組時,都是經過索引來操做的。針對二維數組,使用索引能夠完成對行、列的操做。可是這是很是不直觀的。能夠把二維數組想象成一個excel表格,若是表格沒有列名,操做起來會很是麻煩,針對這種狀況,Numpy提供告終構化數組用來操做每列數據。數組

來看一個示例函數

x = np.array([('Bob', 18, 2000.0),('Tom', 23, 4000.0)],dtype=[('name', 'S10'), ('age', np.int_), ('incom', np.float_)])
x
Out[245]: 
array([(b'Bob', 18, 2000.), (b'Tom', 23, 4000.)],
      dtype=[('name', 'S10'), ('age', '<i4'), ('incom', '<f8')])
x.shape
Out[246]: (2,)
row = x[0]
row
Out[248]: (b'Bob', 18, 2000.)
col = x['name']
col
Out[250]: array([b'Bob', b'Tom'], dtype='|S10')

上面咱們建立了一個二維數組,行數爲2,列數爲3,其中每列的類型分別是長度爲10或者更小的字符串、32位整數、64位浮點數。以後分別使用數字索引訪問了第一行數據獲得row,以及使用名稱索引訪問了第一列數據獲得col。ui

須要注意的是,無論是row仍是col,獲取到的都是隻是視圖,因此更改結構化數組x時,對應的視圖也會發生改變。this

x['name'] = ['Bob01', 'Tom01']
x
Out[252]: 
array([(b'Bob01', 18, 2000.), (b'Tom01', 23, 4000.)],
      dtype=[('name', 'S10'), ('age', '<i4'), ('incom', '<f8')])
row
Out[253]: (b'Bob01', 18, 2000.)
col
Out[254]: array([b'Bob01', b'Tom01'], dtype='|S10')

構建結構化數組

經過dtype對象定義一個結構化數組。使用參數(如提供給dtype函數關鍵字或dtype對象構造函數自己)經過四種可選方法之一指定記錄結構。此參數必須是如下之一:string,tuple,list,或 dictionary。spa

字符串參數excel

在這種狀況下,構造函數須要一個逗號分隔的類型說明符列表,可選地包含額外的形狀信息。字段被賦予默認名稱'f0','f1','f2'等。類型說明符能夠採用4種不一樣的形式:code

a) b1, i1, i2, i4, i8, u1, u2, u4, u8, f2, f4, f8, c8, c16, a<n>
   (表明 bytes, ints, unsigned ints, floats, complex and
    fixed length strings of specified byte lengths)b) int8,...,uint8,...,float16, float32, float64, complex64, complex128
   (this time with bit sizes)c) older Numeric/numarray type specifications (e.g. Float32).
   不推薦使用!d) Single character type specifiers (e.g H for unsigned short ints).
   通常也避免使用!

示例以下:orm

x = np.zeros(3, dtype='3int8, float32, (2,3)float64')
x
Out[256]: 
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=[('f0', 'i1', (3,)), ('f1', '<f4'), ('f2', '<f8', (2, 3))])

元祖參數對象

適用於記錄結構的惟一相關元組是當結構映射到現有數據類型時。這是經過在元組中配對現有數據類型與匹配的dtype定義(使用此處描述的任何變體)來完成的。

x = np.zeros(3, dtype=('i4',[('r','u1'), ('g','u1'), ('b','u1'), ('a','u1')]))
x
Out[258]: 
array([0, 0, 0],
      dtype=(numpy.int32, [('r', 'u1'), ('g', 'u1'), ('b', 'u1'), ('a', 'u1')]))
x['r']
Out[259]: array([0, 0, 0], dtype=uint8)

列表參數

在這種狀況下,記錄結構用元組列表定義。每一個元組具備2或3個元素,指定:字段的名稱(容許使用''),字段的類型,以及形狀(可選)。

x = np.zeros(3, dtype=[('x','f4'),('y',np.float32),('value','f4',(2,2))])
x
Out[261]: 
array([(0., 0., [[0., 0.], [0., 0.]]), (0., 0., [[0., 0.], [0., 0.]]),
       (0., 0., [[0., 0.], [0., 0.]])],
      dtype=[('x', '<f4'), ('y', '<f4'), ('value', '<f4', (2, 2))])

字典參數

容許兩種不一樣的形式。第一個包含一個具備兩個必需鍵('names'和'formats')的字典,每一個鍵都有一個相等大小的值列表。格式列表包含在其餘上下文中容許的任何類型/形狀說明符。名稱必須是字符串。有兩個可選鍵:「offsets」和「titles」。每一個都必須是相應匹配的列表,其中偏移量包含每一個字段的整數偏移量,標題是包含每一個字段的元數據的對象(這些對象沒必要是字符串),其中容許值爲None。舉個例子:

x = np.zeros(3, dtype={'names':['col1', 'col2'], 'formats':['i4','f4']})
x
Out[263]: 
array([(0, 0.), (0, 0.), (0, 0.)],
      dtype=[('col1', '<i4'), ('col2', '<f4')])

容許的其餘字典形式是具備指定類型,偏移和可選標題的元組值的名稱鍵的字典。

x = np.zeros(3, dtype={'col1':('i1',0,'title 1'), 'col2':('f4',1,'title 2')})
x
Out[265]: 
array([(0, 0.), (0, 0.), (0, 0.)],
      dtype=[(('title 1', 'col1'), 'i1'), (('title 2', 'col2'), '<f4')])

訪問字段標題

字段標題提供了一個標準位置來放置字段的關聯信息。他們沒必要是字符串。

x.dtype.fields['col1'][2]
Out[267]: 'title 1'

訪問和修改字段名稱

x.dtype.names
Out[268]: ('col1', 'col2')
x.dtype.names = ('x', 'y')
x
Out[270]: 
array([(0, 0.), (0, 0.), (0, 0.)],
      dtype=[(('title 1', 'x'), 'i1'), (('title 2', 'y'), '<f4')])

一次訪問多個字段

您可使用字段名稱列表一次訪問多個字段:

x = np.array([(1.5, 2.5, (1.0, 2.0)), (3., 4., (4., 5.)), (1., 3., (2., 6.))],
             dtype=[('x', 'f4'), ('y', np.float32), ('value', 'f4', (2, 2))])

請注意,x是使用元組列表建立的。

x[['x','y']]
Out[272]: 
array([(1.5, 2.5), (3. , 4. ), (1. , 3. )],
      dtype=[('x', '<f4'), ('y', '<f4')])
x[['x','value']]
Out[273]: 
array([(1.5, [[1., 2.], [1., 2.]]), (3. , [[4., 5.], [4., 5.]]),
       (1. , [[2., 6.], [2., 6.]])],
      dtype=[('x', '<f4'), ('value', '<f4', (2, 2))])
x[x['y'] == 4]
Out[274]: 
array([(3., 4., [[4., 5.], [4., 5.]])],
      dtype=[('x', '<f4'), ('y', '<f4'), ('value', '<f4', (2, 2))])

字段按請求的順序返回(能夠用來調整數組順序

x[['y','x']]
Out[275]: 
array([(2.5, 1.5), (4. , 3. ), (3. , 1. )],
      dtype=[('y', '<f4'), ('x', '<f4')])

    記錄數組

雖然結構化數組已經可以經過字段索引來操做數組了,記錄數組容許經過Python中屬性的方式(就是以「.」的方式)來操做。

記錄數組也使用特殊的數據類型numpy.record

建立記錄數組的最簡單的方法是使用numpy.rec.array

recordarr = np.rec.array([(1,2.,'Hello'),(2,3.,"World")], dtype=[('foo', 'i4'),('bar', 'f4'), ('baz', 'S10')])
recordarr.bar
Out[277]: array([2., 3.], dtype=float32)
recordarr[1:2]
Out[278]: 
rec.array([(2, 3., b'World')],
          dtype=[('foo', '<i4'), ('bar', '<f4'), ('baz', 'S10')])
recordarr[1:2].foo
Out[279]: array([2])
recordarr.foo[1:2]
Out[280]: array([2])
recordarr[1].baz
Out[281]: b'World'

numpy.rec.array能夠將各類參數轉換爲記錄數組,包括正常的結構化數組:

arr = np.array([(1,2.,'Hello'),(2,3.,"World")], dtype=[('foo', 'i4'), ('bar', 'f4'), ('baz', 'S10')])
recordarr = np.rec.array(arr)
recordarr
Out[285]: 
rec.array([(1, 2., b'Hello'), (2, 3., b'World')],
          dtype=[('foo', '<i4'), ('bar', '<f4'), ('baz', 'S10')])
相關文章
相關標籤/搜索