[英]spark in python: creating an rdd by loading binary data with numpy.fromfile
[英]Restore binary data with numpy fromfile that has been saved with numpy save
我有一個巨大的 3D 陣列(float16),它使用numpy.save
存儲到磁盤。 當我加載它時,它會淹沒我的內存,所以我需要分塊讀取它並逐步處理數據。 但似乎數據是以與保存時不同的維度順序讀取的。 我准備了以下簡單示例:
import numpy as np
myArray = np.zeros((2, 5, 3))
content = np.arange(0,10).reshape((2, 5))
myArray[:,:,0] = content
myArray[:,:,1] = content*10
myArray[:,:,2] = content*100
np.save("myArray.npy", myArray.astype(np.float16))
myArray
是一個 3D 數組,在 z 方向上有 2 行、5 列和 3 個切片。 請注意,沿着z
我在第一個切片中有從 0 到 9 的數字,然后在第二個切片中有 0 到 90,在第三個中有 0 到 900。 通過np.load
加載第一個切片工作正常,但是當我嘗試以下操作時,順序搞砸了:
with open("myArray.npy", mode="rb") as fhandle:
chunknp = np.fromfile(fhandle, count=10, dtype=np.float16)
chunknp = np.resize(chunknp, new_shape=(2, 5, 1))
print(chunknp)
# Out:
>> [[[2.630e+01]
[2.133e+01]
[1.700e+02]
[5.960e-08]
[7.033e-06]]
[[2.922e-02]
[1.380e+03]
[9.535e+02]
[2.908e-02]
[8.255e-03]]]
Count=10
給出了我認為是 z==0 的 2x5 的前 10 個元素。 調整到 (2, 5, 1) 對問題並不重要,但這是我需要的最終順序。 我如何正確提取它?
In [103]: myArray = np.zeros((2, 5, 3))
...: content = np.arange(0,10).reshape((2, 5))
...: myArray[:,:,0] = content
...: myArray[:,:,1] = content*10
...: myArray[:,:,2] = content*100
...:
In [104]: myArray
Out[104]:
array([[[ 0., 0., 0.],
[ 1., 10., 100.],
[ 2., 20., 200.],
[ 3., 30., 300.],
[ 4., 40., 400.]],
[[ 5., 50., 500.],
[ 6., 60., 600.],
[ 7., 70., 700.],
[ 8., 80., 800.],
[ 9., 90., 900.]]])
In [105]: myArray.ravel()
Out[105]:
array([ 0., 0., 0., 1., 10., 100., 2., 20., 200., 3., 30.,
300., 4., 40., 400., 5., 50., 500., 6., 60., 600., 7.,
70., 700., 8., 80., 800., 9., 90., 900.])
使用tostring
顯示相同的順序:
In [108]: np.frombuffer(myArray.tostring(), dtype=float)
Out[108]:
array([ 0., 0., 0., 1., 10., 100., 2., 20., 200., 3., 30.,
300., 4., 40., 400., 5., 50., 500., 6., 60., 600., 7.,
70., 700., 8., 80., 800., 9., 90., 900.])
要選擇存儲數據的連續切片,請在第一個維度上建立索引:
In [112]: myArray[0,:,:]
Out[112]:
array([[ 0., 0., 0.],
[ 1., 10., 100.],
[ 2., 20., 200.],
[ 3., 30., 300.],
[ 4., 40., 400.]])
對最后一次訪問content
值進行索引,但這不是它們在myArray
緩沖區中的存儲方式:
In [113]: myArray[:,:,0]
Out[113]:
array([[0., 1., 2., 3., 4.],
[5., 6., 7., 8., 9.]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.