numpy的文件存储与处理

import numpy as np
from io import StringIO

第二部分 ndarray 文件存储与读取

一维二维数组 可以采用csv(Comma Separated Value 逗号分割值)

”’
1)np.savetxt np.loadtxt

fname : filename or file handle 指定要存入的文件名,支持gzip (.gz .bz2)格式
If the filename ends in .gz, the file is automatically saved in compressed gzip format. loadtxt understands gzipped files transparently(易察觉的).

X : array_like 一个ndarray对象
Data to be saved to a text file.

fmt : str or sequence of strs, optional 制定每个元素要存入的格式
e.g. [‘%.3e + %.3ej’, ‘(%.15e%+.15ej)’] for 2 columns (复数可以这么写 多列)

delimiter : str, optional 每个元素之间的分割符
String or character separating columns.

newline : str, optional 每行的换行符
String or character separating lines.
New in version 1.5.0.
header : str, optional 文件开始时的文本
String that will be written at the beginning of the file.
New in version 1.7.0.
footer : str, optional 文件结束时的文本
String that will be written at the end of the file.
New in version 1.7.0.
comments : str, optional 将header and footer 标注为注释
String that will be prepended to the header and footer strings, to mark them as comments. Default: ‘# ‘, as expected by e.g. numpy.loadtxt.
New in version 1.7.0.
”’
x=np.array([[1,2,3,4],[2,3,4]])#不可存储,用loadtxt读取不了,因为loadtxt必须保证列数相同
np.savetxt(fname=”test1.out”,fmt=”%s”,header=”This is test1.txt”,X=x)
y=np.array([[1,2],[3,4]])
np.savetxt(fname=”test2.out”,fmt=”%d” ,footer=”This is test2.txt”,X=y)
”’

numpy.loadtxt(fname, dtype=float, comments=’#’, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)

Parameters:
fname : file, str, or pathlib.Path
File, filename, or generator to read. If the filename extension is .gz or .bz2, the file is first decompressed. Note that generators should return byte strings for Python 3k.

dtype : data-type, optional
Data-type of the resulting array; default: float. If this is a structured data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array. In this case, the number of columns used must match the number of fields in the data-type.

comments : str or sequence, optional(注释类型 要和savetxt的相对应)
The characters or list of characters used to indicate the start of a comment; default: ‘#’.
delimiter : str, optional
The string used to separate values. By default, this is any whitespace.

converters : dict, optional(解析函数)
A dictionary mapping column number to a function that will convert that column to a float. E.g., if column 0 is a date string: converters = {0: datestr2num}. Converters can also be used to provide a default value for missing data (but see also genfromtxt): converters = {3: lambda s: float(s.strip() or 0)}. Default: None.
skiprows : int, optional
Skip the first skiprows lines; default: 0.
usecols : int or sequence, optional(要提取的列)
Which columns to read, with 0 being the first. For example, usecols = (1,4,5) will extract the 2nd, 5th and 6th columns. The default, None, results in all columns being read.
New in version 1.11.0.

Also when a single column has to be read it is possible to use an integer instead of a tuple. E.g usecols = 3 reads the fourth column the same way as usecols = (3,)` would.
unpack : bool, optional(打包?)
If True, the returned array is transposed, so that arguments may be unpacked using x, y, z = loadtxt(…). When used with a structured data-type, arrays are returned for each field. Default is False.
ndmin : int, optional
The returned array will have at least ndmin dimensions. Otherwise mono-dimensional axes will be squeezed. Legal values: 0 (default), 1 or 2.
New in version 1.6.0.

Returns:
out : ndarray
Data read from the text file.
”’

test1=np.loadtxt(fname=”test2.out”,dtype=int)
print(“test2:”,test1)
x1,x2=np.loadtxt(fname=”test2.out”,dtype=int,unpack=True)
print(“x1,x2:”,x1,x2)
str=StringIO(“Zhang 20 boy\nYu 20 girl”)
struct_dtype=np.dtype({‘names’:(‘name’,’age’,’gender’), ‘formats’:(‘S32’,’i4’,’S32’)},align=True)
str_array=np.loadtxt(fname=str,dtype=struct_dtype)
print(“str_array:”,str_array)

2)多维数组

”’

tofile(self, fid, sep=”“, format=”%s”)

fid : file or str
An open file object, or a string containing a filename.
sep : str 如果为空,则默认为二进制存储
Separator between array items for text output.
If “” (empty), a binary file is written, equivalent to
file.write(a.tobytes()).
format : str 元素类型
Format string for text file output.
Each entry in the array is formatted to text by first converting
it to the closest Python type, and then using “format” % item.

            This is a convenience function for quick storage(存储) of array data.
        Information on endianness(字节序) and precision(精确度) is lost, so this method is not a
        good choice for files intended to(打算) archive data or transport data between
        machines with different endianness. Some of these problems can be overcome
        by outputting the data as text files, at the expense of(在损失....的情况下) speed and file
        size.

”’
y.tofile(file=”tofile.txt”,format=”%d” ,sep=” “)
from_file_array=np.fromfile(file=”tofile.txt”,dtype=int,count=-1,sep=” “)#count=-1默认读取整个文件
print(“from_file_array:”,from_file_array)
reshape_from_file_array=from_file_array.reshape((2,2))
print(“reshape_from_file_array:”,reshape_from_file_array)

3)numpy 自定义格式

np.save(file=”np_save”,arr=y)#默认.npy后缀 其实这个文件打开看一看,第一行是明文的这个ndarray数组的信息,第二行开始是二进制的数据存储
print(“np.load:”,np.load(file=”np_save.npy”))
np.savez_compressed(file=”np_save_compressed”,Y=y)#默认为压缩的.npz格式 y的名字为Y
print(“np.load:”,np.load(file=”np_save_compressed.npz”)[‘Y’])#数组以字典方式进行存储
np.savez(file=”np_save_uncompressed”,Y=y)#默认为非压缩的.npz格式
print(“np.load:”,np.load(file=”np_save_uncompressed.npz”,)[‘Y’])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 你可以使用numpy模块的load函数来导入训练数据的numpy文件,例如: ``` import numpy as np data = np.load('training_data.npy') ``` 这将导入名为“training_data.npy”的numpy数组,并将其存储在变量data中。需要注意的是,你需要确保导入的文件路径和文件名与实际文件的名称和路径相匹配。 ### 回答2: 要导入训练数据的numpy文件,你可以按照以下步骤进行操作: 1. 首先,你需要确保你已经安装了NumPy包。可以通过在命令行界面输入 `pip install numpy` 来安装NumPy。 2. 接下来,你需要将训练数据保存为一个numpy文件。假设你的训练数据保存为名为 `train_data.npy` 的numpy文件。 3. 在Python脚本中,首先导入NumPy包。 ``` import numpy as np ``` 4. 使用NumPy的`load()`函数来加载numpy文件,并将其赋值给一个变量,例如 `train_data`。 ``` train_data = np.load('train_data.npy') ``` 5. 现在,你已经成功地将训练数据从numpy文件导入到了变量 `train_data`中,你可以在接下来的代码中使用它。 这是一个简单的例子,展示了如何导入训练数据的numpy文件。你可以根据自己的具体情况进行调整和修改。希望对你有帮助! ### 回答3: 要导入训练数据的numpy文件,可以按照以下步骤进行: 1. 首先,确保已经安装了NumPy库。如果没有安装,可以通过在命令行中运行`pip install numpy`来安装它。 2. 在Python脚本中导入NumPy库,通过`import numpy as np`来实现。 3. 使用NumPy库的`load()`函数来加载numpy文件。该函数的语法为:`np.load(file_path)`,其中`file_path`是存储训练数据的numpy文件的路径。 4. 将加载的数据存储在一个变量中,以便进一步处理和使用。例如:`data = np.load(file_path)`。 5. 现在,你可以使用`data`变量来访问导入的训练数据。对于多维数组,可以使用索引来访问特定的元素、切片来访问特定区域的数据、以及各种NumPy函数和操作来处理数据。 6. 如果需要将导入的训练数据保存为其他格式(如CSV或文本文件),可以使用NumPy提供的相应函数来实现。例如,使用`np.savetxt()`将数据保存为CSV文件。 综上所述,通过以上步骤,可以导入存储numpy文件中的训练数据并在Python中使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值