【Python載入數(shù)據(jù)】用scipy.io通過mat文件在Python和Matlab/Octave之間進(jìn)行數(shù)據(jù)交換

用scipy.io通過mat文件在Python和Matlab/Octave之間進(jìn)行數(shù)據(jù)交換

點(diǎn)擊打開鏈接

http://docs.scipy.org/doc/scipy/reference/tutorial/io.html

如果更喜歡用python或Octave/Matlab,但又想兼而有之, 可以考慮

File IO (scipy.io)

See also

numpy-reference.routines.io(in numpy)

MATLAB files

loadmat(file_name[,?mdict,?appendmat])Load MATLAB file

savemat(file_name,?mdict[,?appendmat,?...])Save a dictionary of names and arrays into a MATLAB-style .mat file.

whosmat(file_name[,?appendmat])List variables inside a MATLAB file

The basic functions

We’ll start by importingscipy.ioand calling itsiofor convenience:

>>>

>>>importscipy.ioassio

If you are using IPython, try tab completing onsio. Among the many options, you will find:

sio.loadmatsio.savematsio.whosmat

These are the high-level functions you will most likely use when working with MATLAB files. You’ll also find:

sio.matlab

This is the package from whichloadmat,savematandwhosmatare imported. Withinsio.matlab, you will find themiomodule This module contains the machinery thatloadmatandsavematuse. From time to time you may find yourself re-using this machinery.

How do I start?

You may have a.matfile that you want to read into Scipy. Or, you want to pass some variables from Scipy / Numpy into MATLAB.

To save us using a MATLAB license, let’s start inOctave. Octave has MATLAB-compatible save and load functions. Start Octave (octaveat the command line for me):

octave:1>a=1:12a=123456789101112octave:2>a=reshape(a,[134])a=ans(:,:,1)=123ans(:,:,2)=456ans(:,:,3)=789ans(:,:,4)=101112octave:3>save-6octave_a.mata% MATLAB 6 compatibleoctave:4>lsoctave_a.matoctave_a.mat

Now, to Python:

>>>

>>>mat_contents=sio.loadmat('octave_a.mat')>>>mat_contents{'a': array([[[? 1.,? 4.,? 7.,? 10.],[? 2.,? 5.,? 8.,? 11.],[? 3.,? 6.,? 9.,? 12.]]]),'__version__': '1.0','__header__': 'MATLAB 5.0 MAT-file, written byOctave 3.6.3, 2013-02-17 21:02:11 UTC','__globals__': []}>>>oct_a=mat_contents['a']>>>oct_aarray([[[? 1.,? 4.,? 7.,? 10.],[? 2.,? 5.,? 8.,? 11.],[? 3.,? 6.,? 9.,? 12.]]])>>>oct_a.shape(1, 3, 4)

Now let’s try the other way round:

>>>

>>>importnumpyasnp>>>vect=np.arange(10)>>>vect.shape(10,)>>>sio.savemat('np_vector.mat',{'vect':vect})

Then back to Octave:

octave:8>loadnp_vector.matoctave:9>vectvect=0123456789octave:10>size(vect)ans=110

If you want to inspect the contents of a MATLAB file without reading the data into memory, use thewhosmatcommand:

>>>

>>>sio.whosmat('octave_a.mat')[('a', (1, 3, 4), 'double')]

whosmatreturns a list of tuples, one for each array (or other object) in the file. Each tuple contains the name, shape and data type of the array.

MATLAB structs

MATLAB structs are a little bit like Python dicts, except the field names must be strings. Any MATLAB object can be a value of a field. As for all objects in MATLAB, structs are in fact arrays of structs, where a single struct is an array of shape (1, 1).

octave:11>my_struct=struct('field1',1,'field2',2)my_struct={field1=1field2=2}octave:12>save-6octave_struct.matmy_struct

We can load this in Python:

>>>

>>>mat_contents=sio.loadmat('octave_struct.mat')>>>mat_contents{'my_struct': array([[([[1.0]], [[2.0]])]],dtype=[('field1', 'O'), ('field2', 'O')]), '__version__': '1.0', '__header__': 'MATLAB 5.0 MAT-file, written by Octave 3.6.3, 2013-02-17 21:23:14 UTC', '__globals__': []}>>>oct_struct=mat_contents['my_struct']>>>oct_struct.shape(1, 1)>>>val=oct_struct[0,0]>>>val([[1.0]], [[2.0]])>>>val['field1']array([[ 1.]])>>>val['field2']array([[ 2.]])>>>val.dtypedtype([('field1', 'O'), ('field2', 'O')])

In versions of Scipy from 0.12.0, MATLAB structs come back as numpy structured arrays, with fields named for the struct fields. You can see the field names in thedtypeoutput above. Note also:

>>>

>>>val=oct_struct[0,0]

and:

octave:13>size(my_struct)ans=11

So, in MATLAB, the struct array must be at least 2D, and we replicate that when we read into Scipy. If you want all length 1 dimensions squeezed out, try this:

>>>

>>>mat_contents=sio.loadmat('octave_struct.mat',squeeze_me=True)>>>oct_struct=mat_contents['my_struct']>>>oct_struct.shape()

Sometimes, it’s more convenient to load the MATLAB structs as python objects rather than numpy structured arrays - it can make the access syntax in python a bit more similar to that in MATLAB. In order to do this, use thestruct_as_record=Falseparameter setting toloadmat.

>>>

>>>mat_contents=sio.loadmat('octave_struct.mat',struct_as_record=False)>>>oct_struct=mat_contents['my_struct']>>>oct_struct[0,0].field1array([[ 1.]])

struct_as_record=Falseworks nicely withsqueeze_me:

>>>

>>>mat_contents=sio.loadmat('octave_struct.mat',struct_as_record=False,squeeze_me=True)>>>oct_struct=mat_contents['my_struct']>>>oct_struct.shape# but no - it's a scalarTraceback (most recent call last):File"", line1, inAttributeError:'mat_struct' object has no attribute 'shape'>>>type(oct_struct)>>>oct_struct.field11.0

Saving struct arrays can be done in various ways. One simple method is to use dicts:

>>>

>>>a_dict={'field1':0.5,'field2':'a string'}>>>sio.savemat('saved_struct.mat',{'a_dict':a_dict})

loaded as:

octave:21>loadsaved_structoctave:22>a_dicta_dict=scalarstructurecontainingthefields:field2=astringfield1=0.50000

You can also save structs back again to MATLAB (or Octave in our case) like this:

>>>

>>>dt=[('f1','f8'),('f2','S10')]>>>arr=np.zeros((2,),dtype=dt)>>>arrarray([(0.0, ''), (0.0, '')],dtype=[('f1', '>>arr[0]['f1']=0.5>>>arr[0]['f2']='python'>>>arr[1]['f1']=99>>>arr[1]['f2']='not perl'>>>sio.savemat('np_struct_arr.mat',{'arr':arr})

MATLAB cell arrays

Cell arrays in MATLAB are rather like python lists, in the sense that the elements in the arrays can contain any type of MATLAB object. In fact they are most similar to numpy object arrays, and that is how we load them into numpy.

octave:14>my_cells={1,[2,3]}my_cells={[1,1]=1[1,2]=23}octave:15>save-6octave_cells.matmy_cells

Back to Python:

>>>

>>>mat_contents=sio.loadmat('octave_cells.mat')>>>oct_cells=mat_contents['my_cells']>>>print(oct_cells.dtype)object>>>val=oct_cells[0,0]>>>valarray([[ 1.]])>>>print(val.dtype)float64

Saving to a MATLAB cell array just involves making a numpy object array:

>>>

>>>obj_arr=np.zeros((2,),dtype=np.object)>>>obj_arr[0]=1>>>obj_arr[1]='a string'>>>obj_arrarray([1, 'a string'], dtype=object)>>>sio.savemat('np_cells.mat',{'obj_arr':obj_arr})

octave:16>loadnp_cells.matoctave:17>obj_arrobj_arr={[1,1]=1[2,1]=astring}

IDL files

readsav(file_name[,?idict,?python_dict,?...])Read an IDL .sav file

Matrix Market files

mminfo(source)Queries the contents of the Matrix Market file ‘filename’ to extract size and storage information.

mmread(source)Reads the contents of a Matrix Market file ‘filename’ into a matrix.

mmwrite(target,?a[,?comment,?field,?precision])Writes the sparse or dense arrayato a Matrix Market formatted file.

Wav sound files (scipy.io.wavfile)

read(filename[,?mmap])Return the sample rate (in samples/sec) and data from a WAV file

write(filename,?rate,?data)Write a numpy array as a WAV file

Arff files (scipy.io.arff)

Module to read ARFF files, which are the standard data format for WEKA.

ARFF is a text file format which support numerical, string and data values. The format can also represent missing data and sparse data.

See theWEKA websitefor more details about arff format and available datasets.

Examples

>>>

>>>fromscipy.ioimportarff>>>fromcStringIOimportStringIO>>>content="""...@relation foo...@attribute width? numeric...@attribute height numeric...@attribute color? {red,green,blue,yellow,black}...@data...5.0,3.25,blue...4.5,3.75,green...3.0,4.00,red...""">>>f=StringIO(content)>>>data,meta=arff.loadarff(f)>>>dataarray([(5.0, 3.25, 'blue'), (4.5, 3.75, 'green'), (3.0, 4.0, 'red')],dtype=[('width', '>>metaDataset: foowidth's type is numericheight's type is numericcolor's type is nominal, range is ('red', 'green', 'blue', 'yellow', 'black')

loadarff(f)Read an arff file.

Netcdf (scipy.io.netcdf)

netcdf_file(filename[,?mode,?mmap,?version])A file object for NetCDF data.

Allows reading of NetCDF files (version ofpupynerepackage)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末疮鲫,一起剝皮案震驚了整個(gè)濱河市链蕊,隨后出現(xiàn)的幾起案子坠狡,更是在濱河造成了極大的恐慌馍管,老刑警劉巖遭居,帶你破解...
    沈念sama閱讀 206,214評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件厚者,死亡現(xiàn)場離奇詭異勺爱,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)拨匆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門姆涩,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人惭每,你說我怎么就攤上這事骨饿。” “怎么了台腥?”我有些...
    開封第一講書人閱讀 152,543評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵宏赘,是天一觀的道長。 經(jīng)常有香客問我黎侈,道長察署,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,221評(píng)論 1 279
  • 正文 為了忘掉前任峻汉,我火速辦了婚禮贴汪,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘休吠。我一直安慰自己扳埂,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,224評(píng)論 5 371
  • 文/花漫 我一把揭開白布瘤礁。 她就那樣靜靜地躺著阳懂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪柜思。 梳的紋絲不亂的頭發(fā)上岩调,一...
    開封第一講書人閱讀 49,007評(píng)論 1 284
  • 那天,我揣著相機(jī)與錄音酝蜒,去河邊找鬼誊辉。 笑死,一個(gè)胖子當(dāng)著我的面吹牛亡脑,可吹牛的內(nèi)容都是我干的堕澄。 我是一名探鬼主播,決...
    沈念sama閱讀 38,313評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼霉咨,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼蛙紫!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起途戒,我...
    開封第一講書人閱讀 36,956評(píng)論 0 259
  • 序言:老撾萬榮一對(duì)情侶失蹤坑傅,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后喷斋,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體唁毒,經(jīng)...
    沈念sama閱讀 43,441評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蒜茴,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,925評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了浆西。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片粉私。...
    茶點(diǎn)故事閱讀 38,018評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖近零,靈堂內(nèi)的尸體忽然破棺而出诺核,到底是詐尸還是另有隱情,我是刑警寧澤久信,帶...
    沈念sama閱讀 33,685評(píng)論 4 322
  • 正文 年R本政府宣布窖杀,位于F島的核電站,受9級(jí)特大地震影響裙士,放射性物質(zhì)發(fā)生泄漏入客。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,234評(píng)論 3 307
  • 文/蒙蒙 一腿椎、第九天 我趴在偏房一處隱蔽的房頂上張望痊项。 院中可真熱鬧,春花似錦酥诽、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,240評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至边器,卻和暖如春训枢,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背忘巧。 一陣腳步聲響...
    開封第一講書人閱讀 31,464評(píng)論 1 261
  • 我被黑心中介騙來泰國打工恒界, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人砚嘴。 一個(gè)月前我還...
    沈念sama閱讀 45,467評(píng)論 2 352
  • 正文 我出身青樓十酣,卻偏偏與公主長得像,于是被迫代替她去往敵國和親际长。 傳聞我的和親對(duì)象是個(gè)殘疾皇子耸采,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,762評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容

  • !~~~終于開始了在Coursera上的第一個(gè)編程練習(xí) 工育。虾宇。。 下面就是這次作業(yè)的介紹了~: Introducti...
    東皇Amrzs閱讀 9,603評(píng)論 9 7
  • 當(dāng)哈里遇上薩利 第一次見面他說她很迷人她說她討厭他 第二次見面他看見她在和他吻別她以為他認(rèn)不出她 第三次見面他和她...
    沒有人陪你流浪閱讀 446評(píng)論 0 1
  • 說起愛情如绸,讓我想起了茨威格的《一個(gè)陌生女人的來信》這本書嘱朽。 還記得自己曾經(jīng)為書中女子悲慘的一生哭得死去活來旭贬,感...
    櫻花牧道閱讀 454評(píng)論 0 1
  • 我不知道某些文字是不是應(yīng)該被陳述,我不知道有些悲傷該不該被表露搪泳。 奶奶昨天走了稀轨,腦子里一片空白,不知憂傷森书。 沒有地...
    蘑菇蘑菇u閱讀 223評(píng)論 0 0