Python access to npy format data examples

There are two main functions for data processing

(1):np.save("test.npy", data structure) ----Save data

(2):data =np.load('test.npy") ----Get data

Give 2 examples as follows (save the list)

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. Save the dictionary

x-> {0: 'wpy', 1: 'scg'}np.save('test.npy',x)x = np.load('test.npy')x->array({0: 'wpy', 1: 'scg'}, dtype=object)


3. After reading in dictionary format, you need to call the following statement first

data.item()

Convert data numpy.ndarray object to dict

Supplementary knowledge: python read mat or npy file and save mat file as npy file (or npy save as mat) method

Read mat file and save as npy format file

See the code for details, pay attention to the transposition of h5py

import numpy as npfrom scipy import io mat = io.loadmat('yourfile.mat')# If an error is reported: Please use HDF reader for matlab v7.3 files# Change to the next way to read import h5pymat = h5py.File(' yourfile.mat') # There may be multiple cells in the mat file, each corresponding to a dataset # You can use the keys method to view the name of the cell, now you need to use list(mat.keys()),# In addition, you need to read data = mat.get('name'), then you can use Numpy to convert to arrayprint(mat.keys())# You can use the values ​​method to view the information of each cell print(mat.values()) # You can use the shape to view the dimension information print(mat['your_dataset_name'].shape)# Note that the shape information you see here is different from what you opened in matlab# The matrix here is the transposition of the matrix when matlab is opened# So, we need to transpose it back to mat_t = np.transpose(mat['your_dataset_name'])# mat_t is in numpy.ndarray format# then save it as npy format file np.save('yourfile.npy', mat_t)


The reading of npy files is very simple

import numpy as np matrix = np.load('yourfile.npy')

You can re-read the npy file and save it as a mat file

Method one (I encountered an error when double-clicking to open MATLAB: Unable to read MAT-file *********.mat. Not a binary MAT-file. Try load -ASCII to read as text. ):

import numpy as np matrix = np.load('yourfile.npy')f = h5py.File('yourfile.mat','w')f.create_dataset('dataname', data=matrix)# There will be no data Transpose


Method two (using scipy):

from scipy import io mat = np.load('rlt_gene_features.npy-layer-3-train.npy')io.savemat('gene_features.mat', {'gene_features': mat})


The above example of Python accessing npy format data is all the content shared by the editor. I hope to give you a reference, and I hope you can support it.


Guess you like

Origin blog.51cto.com/14825302/2540219