簡介
之前我們操作Numpy的數組時,都是通過索引來操作的。針對二維數組,使用索引可以完成對行、列的操作。但是這是非常不直觀的。可以把二維數組想象成一個excel表格,如果表格沒有列名,操作起來會非常麻煩,針對這種情況,Numpy提供了結構化數組用來操作每列數據。
之前我們操作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。
需要注意的是,不管是row還是col,獲取到的都是只是視圖,所以更改結構化數組x時,對應的視圖也會發生改變。
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。
字符串參數
在這種情況下,構造函數需要一個逗號分隔的類型說明符列表,可選地包含額外的形狀信息。字段被賦予默認名稱'f0','f1','f2'等。類型說明符可以采用4種不同的形式:
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). 一般也避免使用!
示例如下:
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')])