Python 存取npy格式數(shù)據(jù)實(shí)例
數(shù)據(jù)處理的時(shí)候主要通過兩個(gè)函數(shù)
(1):np.save(“test.npy”,數(shù)據(jù)結(jié)構(gòu)) ----存數(shù)據(jù)
(2):data =np.load(’test.npy') ----取數(shù)據(jù)
給2個(gè)例子如下(存列表)
1、
z = [[[1, 2, 3], [’w’]], [[1, 2, 3], [’w’]]]np.save(’test.npy’, z)x = np.load(’test.npy’)x:->array([[list([1, 2, 3]), list([’w’])], [list([1, 2, 3]), list([’w’])]], dtype=object)
2、存字典
x-> {0: ’wpy’, 1: ’scg’}np.save(’test.npy’,x)x = np.load(’test.npy’)x->array({0: ’wpy’, 1: ’scg’}, dtype=object)
3、在存為字典格式讀取后,需要先調(diào)用如下語句
data.item()
將數(shù)據(jù)numpy.ndarray對(duì)象轉(zhuǎn)換為dict
補(bǔ)充知識(shí):python讀取mat或npy文件以及將mat文件保存為npy文件(或npy保存為mat)的方法
讀取mat文件并存為npy格式文件
具體見代碼,注意h5py的轉(zhuǎn)置問題
import numpy as npfrom scipy import iomat = io.loadmat(’yourfile.mat’)# 如果報(bào)錯(cuò):Please use HDF reader for matlab v7.3 files# 改為下一種方式讀取import h5pymat = h5py.File(’yourfile.mat’)# mat文件里可能有多個(gè)cell,各對(duì)應(yīng)著一個(gè)dataset# 可以用keys方法查看cell的名字, 現(xiàn)在要用list(mat.keys()),# 另外,讀取要用data = mat.get(’名字’), 然后可以再用Numpy轉(zhuǎn)為arrayprint(mat.keys())# 可以用values方法查看各個(gè)cell的信息print(mat.values())# 可以用shape查看維度信息print(mat[’your_dataset_name’].shape)# 注意,這里看到的shape信息與你在matlab打開的不同# 這里的矩陣是matlab打開時(shí)矩陣的轉(zhuǎn)置# 所以,我們需要將它轉(zhuǎn)置回來mat_t = np.transpose(mat[’your_dataset_name’])# mat_t 是numpy.ndarray格式# 再將其存為npy格式文件np.save(’yourfile.npy’, mat_t)
npy文件的讀取很簡(jiǎn)單
import numpy as np
matrix = np.load(’yourfile.npy’)
可以重新讀取npy文件保存為mat文件
方法一(在MATLAB雙擊打開時(shí)遇到了錯(cuò)誤:Unable to read MAT-file *********.mat. Not a binary MAT-file. Try load -ASCII to read as text. ):
import numpy as npmatrix = np.load(’yourfile.npy’)f = h5py.File(’yourfile.mat’, ’w’)f.create_dataset(’dataname’, data=matrix)# 這里不會(huì)將數(shù)據(jù)轉(zhuǎn)置
方法二(使用scipy):
from scipy import iomat = np.load(’rlt_gene_features.npy-layer-3-train.npy’)io.savemat(’gene_features.mat’, {’gene_features’: mat})
以上這篇Python 存取npy格式數(shù)據(jù)實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. XML入門的常見問題(一)2. Jsp中request的3個(gè)基礎(chǔ)實(shí)踐3. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?4. IntelliJ IDEA 統(tǒng)一設(shè)置編碼為utf-8編碼的實(shí)現(xiàn)5. Django ORM實(shí)現(xiàn)按天獲取數(shù)據(jù)去重求和例子6. jsp EL表達(dá)式詳解7. idea給項(xiàng)目打war包的方法步驟8. chat.asp聊天程序的編寫方法9. idea修改背景顏色樣式的方法10. idea設(shè)置自動(dòng)導(dǎo)入依賴的方法步驟
