Data from Mathematica import to Python

浪子不回头ぞ 提交于 2019-12-23 04:47:09

问题


I have a text file containing 3 dimensional array(100X100X100) obtained from Mathematica. The data are stored with commas and curly braces.I want to use this text file to analyse and plot the data using Python. How can I import the data in Python? I am currently using Python 2.7 version. What may be the format to store the data in matematica in order to use it in Python?


回答1:


since it pains me to see folks storing so much data in ascii, here is a way to do a binary exchange:

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)

note you can have endian-ness issues if you read/write on different hardware. ( easily handled though )

Edit: for completeness a text exchange using native mathematica format looks like this:

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)

with a couple notes of caution, first eval should not be used on untrused input, secondly this will break if any values use scientific notation, or obviously any mathematica symbolic content. Finally it will undoubtedly be painfully slow for large input. I would seriously only use this if you are stuck with a mathematica file and can not use mathematica to put it to a better format.



来源:https://stackoverflow.com/questions/44173958/data-from-mathematica-import-to-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!