我有一个文本文件,其中包含从Mathematica获得的三维数组(100X100X100)。数据是用逗号和大括号存储的,我想用这个文本文件通过Python来分析和绘制数据。如何在Python中导入数据?我目前使用的是Python 2.7版本。为了在Python中使用matematica,在matematica中存储数据的格式是什么?
发布于 2017-05-25 23:19:23
由于看到人们在ascii中存储如此多的数据让我很痛苦,这里有一种进行二进制交换的方法:
mathematica:
data = RandomReal[{-1, 1}, {3, 4, 5}]
f = OpenWrite["test.bin", BinaryFormat -> True];
BinaryWrite[f, ArrayDepth[data], "Integer32"];
BinaryWrite[f, Dimensions[data], "Integer32"];
BinaryWrite[f, data, "Real64"];
Close[f]
python:
import numpy as np
with open('test.bin','rb') as f:
depth=np.fromfile(f,dtype=np.dtype('int32'),count=1)
dims =np.fromfile(f,dtype=np.dtype('int32'),count=depth)
data =np.reshape(np.fromfile(f,dtype=np.dtype('float64'),
count=reduce(lambda x,y:x*y,dims)),dims)
注意:如果你在不同的硬件上读/写,你可能会遇到字节顺序问题。(不过很容易处理)
编辑:为了完整起见,使用本地mathematica格式的文本交换如下所示:
mathematica:
m = RandomReal[{-1, 1}, {8, 8}]
m >> out.m
python:
with open('out.m','r') as f: text=f.read()
for rep in (('{','['),('}',']')):text=text.replace(rep[0],rep[1])
array=eval(text)
有几个注意事项,第一,eval
不应该用于未转换的输入,第二,如果任何值使用科学记数法,或者显然是任何数学符号内容,这将中断。最后,对于大量的输入,它无疑会非常慢。我会认真地使用它,如果你被一个mathematica文件卡住了,并且不能使用mathematica来把它转换成更好的格式。
https://stackoverflow.com/questions/44173958
复制相似问题