Mathematica中的数据导入到Python [英] Data from Mathematica import to Python

查看:947
本文介绍了Mathematica中的数据导入到Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含从Mathematica获得的三维数组(100X100X100)的文本文件。数据以逗号和大括号存储。我想使用此文本文件使用Python分析和绘制数据。如何在Python中导入数据?我目前正在使用Python 2.7版本。在matematica中存储数据以便在Python中使用它的格式是什么?

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?

推荐答案

因为它让我很难看到人们在ascii中存储了这么多数据,这是一种进行二元交换的方法:

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

mathematica:

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 )

编辑:为了完整性,使用原生mathematica格式的文本交换如下所示:

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

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将其设置为更好的格式,我会认真地使用它。

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.

这篇关于Mathematica中的数据导入到Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆