簡體   English   中英

從具有不同數據類型的緩沖區中讀取 numpy 數組而不復制數組

[英]Reading in numpy array from buffer with different data types without copying array

我將數據編碼為二進制字符串,混合了數據類型。

舉個例子(實際數據要大得多),

data = b'l:\x00\x00\xc0\xff|:g\x8em\xbf}:\xceUq\xbf'

我正在將其讀入一個 numpy 數組:

buffer = np.frombuffer(np.array(data), dtype='B')

這使

array([108,  58,   0,   0, 192, 255, 124,  58, 103, 142, 109, 191, 125,
    58, 206,  85, 113, 191], dtype=uint8)

我需要把它改成(np.uint16, np.float) ,所以上面的數組是

[(14956,NaN),(14972,-0.9280),(14973,-0.9427)]

我可以使用單一數據類型的視圖,例如buffer.view(dtype=np.uint16)給出

array([14956,     0, 65472, 14972, 36455, 49005, 14973, 21966, 49009], dtype=uint16)

但是,不要認為我可以將數據類型的組合用於這樣的視圖。 我試過重塑和切片,

buffer = buffer.reshape((3,-1))
firstData = buffer[:,:2]
firstData = array([[108,  58],
                   [124,  58],
                   [125,  58]], dtype=uint8)
firstData.view(dtype = np.uint16)
ValueError: new type not compatible with array.

正如文檔中所暗示的,這可以通過復制來解決

firstData = firstData.copy()
firstData.view(dtype=np.uint16)
array([[14956],
       [14972],
       [14973]], dtype=uint16)

有沒有一種快速的方法可以在不復制數組的情況下做到這一點?

使用具有兩個字段的結構化數據類型:

In [89]: data = b'l:\x00\x00\xc0\xff|:g\x8em\xbf}:\xceUq\xbf'

In [90]: dt = np.dtype([('a', np.uint16), ('b', np.float32)])

In [91]: x = np.frombuffer(data, dtype=dt)

In [92]: x
Out[92]: 
array([(14956,         nan), (14972, -0.92795414), (14973, -0.94271553)], 
      dtype=[('a', '<u2'), ('b', '<f4')])

x是一維結構化數組 x中的每一項都是一個具有字段ab的結構體:

In [93]: x[0]
Out[93]: (14956,  nan)

In [94]: x['a']
Out[94]: array([14956, 14972, 14973], dtype=uint16)

請注意,我使用np.float32作為浮點字段。 np.float是 Python 內置float的別名。 如果您將其用作數據類型,numpy 會將其視為 64 位浮點數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM