Ani*_*ish 2 python matlab numpy fread
我有一个二进制文件,我可以在MATLAB中打开,但无法在Python中打开.二进制文件被编码为'双浮点',因此由MATLAB读取,具有以下行:
fread(fopen(fileName), 'float64');
Run Code Online (Sandbox Code Playgroud)
在Python中,我不确定如何复制这一行.我认为使用Numpy将是一个很好的起点,所以我尝试了以下几行,但没有得到我预期的输出.每行有6个数字,我只得到第一个和一个'NaN'.
from numpy import *
f = open('filename', 'rb')
a = fromfile(f, double64, 10)
print a
Run Code Online (Sandbox Code Playgroud)
对此的任何帮助都将非常感激; 我在下面的评论中发布了二进制文件和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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)