python numpy读取数据_Python numpy数据的保存和读取

在科学计算的过程中,往往需要保存一些数据,也经常需要把保存的这些数据加载到程序中,在 Matlab 中我们可以用 save 和 lood 函数很方便的实现。类似的在 Python 中,我们可以用 numpy.save() 和 numpy.load() 函数达到类似的效果,并且还可以用 scipy.io.savemat() 将数据保存为 .mat 格式,用scipy.io.loadmat() 读取 .mat 格式的数据,达到可以和 Matlab 或者Octave 进行数据互动的效果.

下面分别介绍之:

numpy.save()

Save an array to a binary file in NumPy ``.npy`` format.

Parameters

----------

file : file, str, or pathlib.Path

File or filename to which the data is saved. If file is a file-object,

then the filename is unchanged. If file is a string or Path, a ``.npy``

extension will be appended to the file name if it does not already

have one.

arr : array_like

Array data to be saved.

allow_pickle : bool, optional

Allow saving object arrays using Python pickles. Reasons for disallowing

pickles include security (loading pickled data can execute arbitrary

code) and portability (pickled objects may not be loadable on different

Python installations, for example if the stored objects require libraries

that are not available, and not all pickled data is compatible between

Python 2 and Python 3).

Default: True

fix_imports : bool, optional

Only useful in forcing objects in object arrays on Python 3 to be

pickled in a Python 2 compatible way. If `fix_imports` is True, pickle

will try to map the new Python 3 names to the old module names used in

Python 2, so that the pickle data stream is readable with Python 2.

See Also

--------

savez : Save several arrays into a ``.npz`` archive

savetxt, load

Notes

-----

For a description of the ``.npy`` format, see :py:mod:`numpy.lib.format`.

Examples

--------

>>> from tempfile import TemporaryFile

>>> outfile = TemporaryFile()

>>> x = np.arange(10)

>>> np.save(outfile, x)

>>> outfile.seek(0) # Only needed here to simulate closing & reopening file

>>> np.load(outfile)

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

示例:

import numpy as np

a=np.mat('1,2,3;4,5,6')

b=np.array([[1,2,3],[4,5,6]])

np.save('a.npy',a)

np.save('b.npy',b)

numpy.load()

Wrapper around cPickle.load which accepts either a file-like object or

a filename.

Note that the NumPy binary format is not based on pickle/cPickle anymore.

For details on the preferred way of loading and saving files, see `load`

and `save`.

See Also

--------

load, save

示例:

data_a=np.load('a.npy')

data_b=np.load('b.npy')

print ('data_a \n',data_a,'\n the type is',type(data_a))

print ('data_b \n',data_a,'\n the type is',type(data_b))

data_a

[[1 2 3]

[4 5 6]]

the type is

data_b

[[1 2 3]

[4 5 6]]

the type is

我们可以看到这一过程把原本为矩阵的 a 变为数组型了

如果想同时保存 a b 到同一个文件,我们可以用 np.savez() 函数,具体用法如下:

np.savez('ab.npz',k_a=a,k_b=b)

c=np.load('ab.npz')

print (c['k_a'])

print (c['k_b'])

[[1 2 3]

[4 5 6]]

[[1 2 3]

[4 5 6]]

这时的 c 是一个字典,需要通过关键字取出我们需要的数据

下面我们来认识下 scipy.io.savemat() 和 scipy.io.loadmat()

首先我们用 scipy.io.savemat() 创建 .mat 文件,该函数有两个参数,一个文件名和一个包含变量名和取值的字典.

import numpy as np

from scipy import io

a=np.mat('1,2,3;4,5,6')

b=np.array([[1,1,1],[2,2,2]])

io.savemat('a.mat', {'matrix': a})

io.savemat('b.mat', {'array': b})

至此 Python 的当前工作路径下就多了 a.mat 和 b.mat 这两个文件.

下面我们用 Matlab 读取这两个文件

可以看到 Matlab 已成功读取 Python 生成的 .mat 文件.

watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9nYW9taW5nLmJsb2cuY3Nkbi5uZXQ=,size_16,color_FFFFFF,t_70

我们在来看看 Python 是怎么读取 .mat 文件的。首先来读取刚才生成的 a.mat

c=io.loadmat('a.mat')

print (type(c))

print (c)

dict {‘version’: ‘1.0’, ‘globals’: [], ‘header’: b’MATLAB

5.0 MAT-file Platform: nt, Created on: Tue Aug 4 16:49:28 2015’, ‘a_matrix’: array([[1, 2, 3],[4, 5, 6]])}

所以 Python 读取.mat 文件后返回的是个字典,如果要访问里面的值,就要用到关键字,如:

print(c['a_matrix'])

[[1 2 3] [4 5 6]]

当然了,Python 也可以读取 Matlab 创建的 .mat 文件,从而可以把他们设置在同一工作路径下,在必要的时候进行数据的共享.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python中使用numpy库可以读取Excel数据,具体步骤如下: 1. 安装numpy库 可以使用pip命令安装numpy库,命令如下: ``` pip install numpy ``` 2. 导入numpy库 在Python代码中导入numpy库,命令如下: ``` import numpy as np ``` 3. 使用numpy读取Excel数据 使用numpy库中的loadtxt函数可以读取Excel数据,命令如下: ``` data = np.loadtxt('data.xlsx', delimiter=',', skiprows=1) ``` 其中,data.xlsx是Excel文件名,delimiter是分隔符,skiprows是跳过的行数。 读取完成后,数据会存储在一个numpy数组中,可以使用numpy库中的各种函数进行处理和分析。 ### 回答2: Python是一种强大的编程语言,它能够以多种方式读取和处理数据。其中,使用NumPy库可以更简单、更高效地读取Excel数据NumPy是一种基于Python编程语言的开源数值计算库。它通过使用Python的元组、列表和数组存储数据,可以快速进行多维数组运算。 首先,我们需要安装NumPy库。可以通过在终端运行以下命令来安装: ``` pip install numpy ``` 安装完成后,我们就可以开始读取Excel数据了。我们需要使用NumPy库中的 `genfromtxt` 方法来加载Excel数据。 下面是读取Excel文件的示例代码: ``` import numpy as np data = np.genfromtxt('filename.xlsx', delimiter=',', skip_header=1, filling_values=999) ``` 在这个示例代码中,我们使用 `genfromtxt` 方法读取了Excel文件,并将其存储在 `data` 变量中。在 `genfromtxt` 方法中,我们使用了许多参数来控制读取和转换数据的行为。 - `filename.xlsx` :指定要读取的Excel文件名。注意,这里的文件名需要包含文件扩展名。 - `delimiter` :指定数据分隔符。在这个例子中,我们使用了逗号作为分隔符,因为Excel默认使用逗号分隔数据。 - `skip_header` :指定要跳过读取的行数。在这个例子中,我们跳过了第一行标题行。 - `filling_values` :指定填充值。在这个例子中,我们将缺失的数据填充为了999。 读取Excel数据后,我们可以使用NumPy的各种函数和方法来处理和分析数据。例如,我们可以计算数据的平均值、中位数、标准差等统计量。 总之,使用PythonNumPy库可以轻松地读取Excel数据,并且可以使用丰富的工具和函数来分析和处理数据。这使得Python成为一种强大的数据分析和科学计算工具。 ### 回答3: Python是一种高效的程序设计语言,其对于科学计算和数据处理应用非常常用。在数据处理方面,Python有很多优秀的库可以使用。其中一个广泛使用的库就是numpynumpyPython中对于数值计算和矩阵运算的标准库,numpy提供了向量和矩阵的高效运算,其强大的运算速度和广泛的应用场景是numpy的最大优势。在numpy中,读取excel数据也是一个常见的操作。下面是介绍Python numpy读取excel数据的方法和具体步骤: 1. 安装numpy库 在Python读取excel数据,需要先安装numpy库。在命令行输入以下命令安装numpy: pip install numpy 2. 导入numpy库 在Python程序中,首先需要导入numpy库以便使用其对excel文件的读写操作。使用以下代码: import numpy as np 3. 读取excel数据 使用numpy读取excel数据需要借助python excel库xlrd。xlrd是python中的一个第三方库,可以用来对Excel文件进行读操作。使用以下代码读取excel文件: import xlrd wb = xlrd.open_workbook('file.xlsx') sheet = wb.sheet_by_index(0) 4. 将数据导入numpy数组 读取excel文件后,需要将其数据导入到numpy数组中,以便进行后续的数值计算和矩阵计算。将excel文件中的数据转化为numpy数组,可以使用以下代码: data = [] for i in range(sheet.nrows): row_data = [] for j in range(sheet.ncols): row_data.append(sheet.cell_value(i,j)) data.append(row_data) data_array = np.array(data) 5. 操作和保存 使用numpy读取excel数据后,可以方便的进行各种基于数值计算和矩阵运算的操作。在操作完成后,也可以将操作后的数据保存到excel文件。使用以下代码保存数组到excel文件: import xlwt workbook = xlwt.Workbook(encoding ='ascii') worksheet = workbook.add_sheet('Sheet 1') for i in range(data_array.shape[0]): for j in range(data_array.shape[1]): worksheet.write(i, j, data_array[i, j]) workbook.save('newfile.xlsx') 总之,使用Python numpy读取excel文件是一种简洁、快速和有效的方法。通过numpy包提供的数值计算和矩阵运算,可以方便地处理和分析excel文件中的大量数据。并且numpy还提供了保存文件的功能,可以方便地保存处理好的结果。numpy包除了读写excel文件,还能处理csv文件、文本文档等等数据类型。最重要的是,Pythonnumpy是免费和开源的,使得使用numpy来进行数据处理的应用程序变得方便、快捷和高效。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值