内容来源:
组队学习datawhale.club![6b9b8f4e779839a89eb8e77b72c9c4ac.png](https://img-blog.csdnimg.cn/img_convert/6b9b8f4e779839a89eb8e77b72c9c4ac.png)
import numpy as np
- npy格式:以二进制的方式存储文件,在二进制文件第一行以文本形式保存了数据的元信息(ndim,dtype,shape等),可以用二进制工具查看内容。
- npz格式:以压缩打包的方式存储文件,可以用压缩软件解压
np的读取和保存
- 读取: numpy.save(file, arr, allow_pickle=True, fix_imports=True) Save an array to a binary file in NumPy .npy format.
- 保存: numpy.load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, encoding='ASCII') Load arrays or pickled objects from .npy, .npz or pickled files.
outfile = r'test.npy'
np.random.seed(88)
x = np.random.uniform(0,1,[3,5])# 均匀分布
np.save(outfile,x)
y = np.load(outfile)
y
array([[0.64755105, 0.50714969, 0.52834138, 0.8962852 , 0.69999119],
[0.7142971 , 0.71733838, 0.22281946, 0.17515452, 0.45684149],
[0.92873843, 0.00988589, 0.08992219, 0.85020027, 0.48562106]])
保存一系列数组
- 函数: numpy.savez(file, *args, **kwds) Save several arrays into a single file in uncompressed .npz format.,第一个参数是输出的文件名,随后参数都是需要保存的数组,不写关键字参数的话,数组默认是arr_0开始命名
- 输出的是一个压缩文件,扩展名为npz,但是npz压缩文件中的每一个文件都是save()类型保存的npy文件,文件的名字就是数组名字
- load()自动识别npz文件,并且返回一个类似于字典的对象,可以通过数组名作为关键字获取数组的内容。
outfile = r'.test.npz'
x = np.linspace(0, np.pi, 5)
y = np.sin(x)
z = np.cos(x)
np.savez(outfile, x, y, z_d=z)
data = np.load(outfile)
np.set_printoptions(suppress=True)
data.files
['z_d', 'arr_0', 'arr_1']
print(data['arr_0'])
# [0. 0.78539816 1.57079633 2.35619449 3.14159265]
print(data['arr_1'])
# [0. 0.70710678 1. 0.70710678 0. ]
print(data['z_d'])
# [ 1. 0.70710678 0. -0.70710678 -1. ]
[0. 0.78539816 1.57079633 2.35619449 3.14159265]
[0. 0.70710678 1. 0.70710678 0. ]
[ 1. 0.70710678 0. -0.70710678 -1. ]
文本文件处理
- savetxt(),loadtxt()和genfromtxt()函数用来存储和读取文本文件(如TXT,CSV等)。genfromtxt()比loadtxt()更加强大,可对缺失数据进行处理。
- numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='n', header='', footer='', comments='# ', encoding=None) Save an array to a text file.
- fname:文件路径
- X:存入文件的数组。
- fmt:写入文件中每个元素的字符串格式,默认’%.18e’(保留18位小数的浮点数形式)。
- delimiter:分割字符串,默认以空格分隔。
- numpy.loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None) Load data from a text file.
- fname:文件路径。
- dtype:数据类型,默认为float。
- comments: 字符串或字符串组成的列表,默认为# , 表示注释字符集开始的标志。
- skiprows:跳过多少行,一般跳过第一行表头。
- usecols:元组(元组内数据为列的数值索引), 用来指定要读取数据的列(第一列为0)。
- unpack:当加载多列数据时是否需要将数据列进行解耦赋值给不同的变量。
- numpy.genfromtxt(fname, dtype=float, comments='#', delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None, excludelist=None, deletechars=''.join(sorted(NameValidator.defaultdeletechars)), replace_space='_', autostrip=False, case_sensitive=True, defaultfmt="f%i", unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None, encoding='bytes') Load data from a text file, with missing values handled as specified.names:设置为True时,程序将把第一行作为列名称
# txt文件
outfile = r'test.txt'
x = np.arange(0, 10).reshape(2, -1)
np.savetxt(outfile, x,fmt='%.4f')
y = np.loadtxt(outfile)
print(y)
[[0. 1. 2. 3. 4.]
[5. 6. 7. 8. 9.]]
# csv文件
outfile = r'test.csv'
x = np.arange(0, 10, 0.5).reshape(4, -1)
np.savetxt(outfile, x, fmt='%.3f', delimiter=',')
y = np.loadtxt(outfile, delimiter=',')
print(y)
[[0. 0.5 1. 1.5 2. ]
[2.5 3. 3.5 4. 4.5]
[5. 5.5 6. 6.5 7. ]
[7.5 8. 8.5 9. 9.5]]
# 导入
outfile = r'data.csv'
x = np.loadtxt(outfile, delimiter=',', skiprows=1)
print(x)
x = np.loadtxt(outfile, delimiter=',', skiprows=1, usecols=(1, 2))
print(x)
val1, val2 = np.loadtxt(outfile, delimiter=',', skiprows=1, usecols=(1, 2), unpack=True)#输出按列元组话分配
print(val1) # [123. 110. 164.]
print(val2) # [1.4 0.5 2.1]
[[ 1. 123. 1.4 23. ]
[ 2. 110. 0.5 18. ]
[ 3. 164. 2.1 19. ]]
import numpy as np
outfile = r'.data.csv'
x = np.genfromtxt(outfile, delimiter=',', names=True)
print(x)
# [(1., 123., 1.4, 23.) (2., 110., 0.5, 18.) (3., 164., 2.1, 19.)]
print(type(x))
# <class 'numpy.ndarray'>
print(x.dtype)
# [('id', '<f8'), ('value1', '<f8'), ('value2', '<f8'), ('value3', '<f8')]
print(x['id']) # [1. 2. 3.]
print(x['value1']) # [123. 110. 164.]
print(x['value2']) # [1.4 0.5 2.1]
print(x['value3']) # [23. 18. 19.]
[[123. 1.4]
[110. 0.5]
[164. 2.1]]
[123. 110. 164.]
[1.4 0.5 2.1]
文本输出格式选择
np.set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None, sign=None, floatmode=None, --kwarg) #设置打印选项 recision:int or None浮点输出的精度位数(默认8)# 如floatmode不是fixed,可能是None
threshold:int触发汇总的数组元素总数而不是完整的repr(默认1000) edgeitems:int在开头和结尾的摘要中的数组项数 每个维度(默认为3) linewidth:int每行用于插入的字符数# 换行符(默认为75) suppress : bool,科学记数法启用 # True用固定点打印浮点数符号,当前精度中的数字等于零将打印为零。 # False用科学记数法;最小数绝对值是<1e-4或比率最大绝对值> 1e3。默认值False nanstr:str浮点非字母数字的字符串表示形式(默认为nan) infstr:str浮点无穷大字符串表示形式(默认inf) sign:string,' - ','+'或'',控制浮点类型符号的打印。 # '+'打印正值标志。''打印空格。' - '省略正值符号,默认
formatter:可调用字典,格式化功能 # 格式化设置类型: - 'bool' - 'int' - 'timedelta':'numpy.timedelta64' - 'datetime':numpy.datetime64 - 'float' - 'longfloat':128位浮点数 - 'complexfloat' - 'longcomplexfloat':由两个128位浮点组成 - 'numpystr' : types numpy.string_ and numpy.unicode_ - 'object' : np.object_ arrays - 'str':所有其他字符串
# 用于一次设置一组类型的其他键:
- 'all':设置所有类型
- 'int_kind':设置'int'
- 'float_kind':设置'float'和'longfloat'
- 'complex_kind':设置'complexfloat'和'longcomplexfloat'
- 'str_kind':设置'str'和'numpystr'
floatmode:str控制precision选项的解释 #浮点类型值: -'fixed':始终打印精确的'precision精度'小数位 -'unique':打印最小小数位数,precision选项被忽略。 -'maxprec':打印最多precision小数位数 -'maxprec_equal':最多打印precision小数位数
legacy:string或False # 如为字符串“1.13”,则启用1.13传统打印模式。 # 如设置“False”,禁用传统模式。无法识别的字符串将被忽略
- numpy.get_printoptions() Return the current print options.返回之前的所有参数
# 输出设置
np.set_printoptions(threshold=20)
x = np.arange(50)
print(x) # [ 0 1 2 ... 47 48 49]
np.set_printoptions(threshold=np.iinfo(np.int).max)
print(x)
# [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
# 48 49]
eps = np.finfo(float).eps
x = np.arange(4.)
x = x ** 2 - (x + eps) ** 2
print(x)
# [-4.9304e-32 -4.4409e-16 0.0000e+00 0.0000e+00]
np.set_printoptions(suppress=True)
print(x) # [-0. -0. 0. 0.]
x = np.linspace(0, 10, 10)
print(x)
# [ 0. 1.1111 2.2222 3.3333 4.4444 5.5556 6.6667 7.7778 8.8889
# 10. ]
np.set_printoptions(precision=2, suppress=True, threshold=5)
print(x) # [ 0. 1.11 2.22 ... 7.78 8.89 10. ]
[ 0 1 2 ... 47 48 49]
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
48 49]
[-0. -0. 0. 0.]
[-0. -0. 0. 0.]
[ 0. 1.11 2.22 3.33 4.44 5.56 6.67 7.78 8.89 10. ]
[ 0. 1.11 2.22 ... 7.78 8.89 10. ]
import numpy as np
x = np.get_printoptions()
print(x)
{'edgeitems': 3, 'threshold': 5, 'floatmode': 'maxprec', 'precision': 2, 'suppress': True, 'linewidth': 75, 'nanstr': 'nan', 'infstr': 'inf', 'sign': '-', 'formatter': None, 'legacy': False}
作业
第一题: 只打印或显示numpy数组rand_arr的小数点后3位。
- rand_arr = np.random.random([5, 3])【知识点:输入和输出】如何在numpy数组中只打印小数点后三位?
第二题: 将numpy数组a中打印的项数限制为最多6个元素。【知识点:输入和输出】
第三题:打印完整的numpy数组a而不中断。【知识点:输入和输出】
rand_arr = np.random.random([5,3])
# 第一题: 设置浮点精度
np.set_printoptions(precision=3)
print(rand_arr)
# 第二题:设置输出元素个数
rand_arr = np.arange(10)
np.set_printoptions(edgeitems=3)#edgeitems=nums,nums就是左右两边省略的数
print(rand_arr)
[0 1 2 ... 7 8 9]
# 打印完整函数不中断
rand_arr = np.arange(10)
np.set_printoptions(threshold=float('inf'))
print(rand_arr)
[0 1 2 3 4 5 6 7 8 9]