簡體   English   中英

相當於Matlab的fread()'float64'在Python中

[英]Equivalent of Matlab's fread() 'float64' in Python

我有一個二進制文件,我可以在MATLAB中打開,但無法在Python中打開。 二進制文件被編碼為'雙浮點',因此由MATLAB讀取,具有以下行:

fread(fopen(fileName), 'float64'); 

在Python中,我不確定如何復制這一行。 我認為使用Numpy將是一個很好的起點,所以我嘗試了以下幾行,但沒有得到我預期的輸出。 每行有6個數字,我只得到第一個和一個'NaN'。

from numpy import * 
f = open('filename', 'rb') 
a = fromfile(f, double64, 10)
print a

對此的任何幫助都將非常感激; 我在下面的評論中發布了二進制文件和MATLAB解析文件。 我也不需要特別使用Numpy,我對任何基於Python的解決方案都持開放態度。 謝謝。

每秒的值都是nan所以這可能是一些分隔符。 此外,文件中的值是列優先。 以下腳本讀入數據,拋出NaN條目,將數組操作為正確的形狀,並輸出與您發布的文件相同的CSV文件:

import csv
import numpy as np

# Pull in all the raw data.
with open('TEMPO3.2F-0215_s00116.dat', 'rb') as f:
    raw = np.fromfile(f, np.float64)

# Throw away the nan entries.
raw = raw[1::2]

# Check its a multiple of six so we can reshape it.
if raw.size % 6:
    raise ValueError("Data size not multiple of six.")

# Reshape and take the transpose to manipulate it into the
# same shape as your CSV. The conversion to integer is also
# so the CSV file is the same.
data = raw.reshape((6, raw.size/6)).T.astype('int')

# Dump it out to a CSV.
with open('test.csv', 'w') as f:
    w = csv.writer(f)
    w.writerows(data)

編輯 :更新版本,其中包含jorgeca建議的更改

import csv
import numpy as np

# Pull in all the raw data.
raw = np.fromfile('TEMPO3.2F-0215_s00116.dat', np.float64)

# Throw away the nan entries.
raw = raw[1::2]

# Reshape and take the transpose to manipulate it into the
# same shape as your CSV. The conversion to integer is also
# so the CSV file is the same.
data = raw.reshape((6, -1)).T.astype('int')

# Dump it out to a CSV.
with open('test.csv', 'w') as f:
    w = csv.writer(f)
    w.writerows(data)

在數據值之間存在分隔符,在讀取時產生交替數據和NaN,例如在matlab中:

 NaN
2134
 NaN
2129
 NaN
2128
....
1678

和numpy:

[   nan  2134.    nan ...,  1681.    nan  1678.]

我使用您使用Matlab或numpy(1.7)發布的代碼獲得相同的輸入。 請注意,根據csv文件中的模式,數據是按列逐列讀取的,而不是按行讀取的。

要在numpy中獲取所有數據,請嘗試

a = fromfile(file=f, dtype=float64, count=-1)

暫無
暫無

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

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