Numpy组队学习1-输入和输出
一、npy和npz格式文件的保存及加载:np.save(),np.load()和np.savez()函数
1.保存文件:np.save():Save an array to a binary file in NumPy .npy format.
详细参数:np.save(file, array, allow_pickle=False, fix_imports=True)
前2个参数最常用,file是保存到的文件,array是要保存的数组
2.加载文件:np.load():Load arrays or pickled objects from .npy, .npz or pickled files.
详细参数:numpy.load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, encoding=‘ASCII’)
outfile = r'.\test.npy'
np.random.seed(20200611)
x = np.random.uniform(0, 1, [3,5]) #从[0, 1]的均匀分布中选取3x5个数
np.save(outfile, x)
np.set_printoptions(precision=2) #保留小数点后2位,不然太长了
print(x)
# [[0.2 0.89 0.53 0.61 0.65]
# [0.32 0.12 0.25 0.42 0.58]
# [0.02 0.31 0.47 0.15 0.59]]
print(x.dtype)
#float64
y = np.load(outfile)
print(y)
# [[0.2 0.89 0.53 0.61 0.65]
# [0.32 0.12 0.25 0.42 0.58]
# [0.02 0.31 0.47 0.15 0.59]]
print(y.dtype)
#float64
执行完上述代码后,可以在左侧project下看到已经生产了一个test.npy文件。
3.将多个文件保存为一个.npz压缩包:np.savez():Save several arrays into a single file in uncompressed .npz format.
详细参数:numpy.savez(file, *args, **kwds)
x = np.linspace(0, np.pi, 5) #从0到π的5个等分点
y = np.sin(x)
z = np.cos(x)
outfile = r'.\test.npz'
#文件名后缀必须是npz,否则使用np.savez(outfile)会报错!
np.savez(outfile, x, y, z_d=z)
#用解压软件打开 test.npz 文件,会发现其中有三个文件:arr_0.npy,arr_1.npy,z_d.npy,其中分别保存着数组x,y,z的内容。
#load()自动识别npz文件,并且返回一个类似于字典的对象,可以通过数组名作为关键字获取数组的内容。
data = np.load(outfile)
np.set_printoptions(suppress=True)
print(data)
#<numpy.lib.npyio.NpzFile object at 0x000002A3D564C888>
print(data.files)
#['z_d', 'arr_0', 'arr_1']
#若无z_d=z 则为['arr_0', 'arr_1', 'arr_2']
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. ]
注意点:np.save()必须与npy一起用,np.savez()必须与npz一起用,否则会报错!!
二、文本文件(txt,csv)的保存和加载:np.savetxt(),np.loadtxt(),np.genfromtxt()
1.np.savetxt()和np.loadtxt(),使用与np.save()和np.savez()相似,但是文件名的后缀必须为txt或csv。注意,np.savetxt()虽然名字里有txt,但是只要文件名为csv,也是可以生成csv格式文件的。
import numpy as np
outfile = r'.\test.txt'
x = np.arange(0, 10).reshape(2, -1)
print(x)
#[[0 1 2 3 4]
#[5 6 7 8 9]]
np.savetxt(outfile, x)
y = np.loadtxt(outfile)
print(y)
#[[0. 1. 2. 3. 4.]
#[5. 6. 7. 8. 9.]]
#在左侧就可双击打开test.txt文件!
np.savetxt()中的fmt,delimiter参数:
fmt:写入文件中每个元素的字符串格式,默认’%.18e’(保留18位小数的浮点数形式)。
delimiter:分割字符串,默认以空格分隔。
outfile = r'.\test1.csv'
x = np.arange(0, 10, 0.5).reshape(4, -1)
print(x)
# [[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]]
np.savetxt(outfile, x, fmt='%.3f', delimiter=',')
y = np.loadtxt(outfile,delimiter=',')
#此处亲自测试:上2行的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]]
np.loadtxt()中的skiprows,usecols,unpack参数(看例子理解)
skiprows:跳过多少行,一般跳过第一行表头
usecols:元组(元组内数据为列的数值索引), 用来指定要读取数据的列(第一列为0)
unpack:解构各列,分别赋值给各变量
import numpy as np
outfile = r'.\data.csv'
#这个data.csv是我在pycharm中自己加的,不是从excel中加的!
# 在左上角File->New->File->data.csv,然后将网站里的内容复制进去。发现创建了一个csv文件,外部也可以打开!
x= np.loadtxt(outfile, delimiter=',', skiprows=1) #skiprows:跳过多少行,一般跳过第一行表头。
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) #float64
x = np.loadtxt(outfile, delimiter=',', skiprows=1, usecols=(1, 2)) #usecols:元组(元组内数据为列的数值索引), 用来指定要读取数据的列(第一列为0)。
print(x)
# [[123. 1.4]
# [110. 0.5]
# [164. 2.1]]
val1, val2 = np.loadtxt(outfile, delimiter=',', skiprows=1, usecols=(1, 2), unpack=True) #将两列分别赋值给val1,val2
print(val1, val2)
# [123. 110. 164.] [1.4 0.5 2.1]
2.np.genfromtxt():与np.loadtxt()类似,是np.loadtxt()的升级版,是面向结构数组和缺失数据处理的。Load data from a text file, with missing values handled as specified.
import numpy as np
outfile = r'.\data.csv'
x = np.genfromtxt(outfile, delimiter=',', names=True) #names:设置为True时,程序将把第一行作为列名称。
print(x)
#[(1., 123., 1.4, 23.) (2., 110., 0.5, 18.) (3., 164., 2.1, 19.)]
#可以看到,虽然loadtxt和genfromtxt对outfile做了类似的处理,但是输出不尽相同!
print(type(x)) #<class 'numpy.ndarray'>
print(x.dtype) #[('id', '<f8'), ('value1', '<f8'), ('value2', '<f8'), ('value3', '<f8')]
#x.dtype的也与上方loadtxt对应的输出不同!
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.]
#缺失数据的例子:data1.csv
outfile = r'.\data1.csv'
x= np.genfromtxt(outfile, delimiter=',', names=True)
print(x)
#[(1., 123., 1.4, 23.) (2., 110., nan, 18.) (3., nan, 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. nan]
print(x['value2']) # [1.4 nan 2.1]
print(x['value3']) # [23. 18. 19.]
#例子中并没有填充缺失数据…………
三、文本格式选项:np.set_printoptions()的使用
主要讲了3个:
1.precision:设置浮点精度,控制输出的小数点个数,默认是8。
2.threshold:概略显示,数组中最大值若超过该值,则以“…”的形式来表示,默认是1000。
3.当suppress=True,表示小数不需要以科学计数法的形式输出,默认是False。
4.最后补充了np.get_printoptions(),是get不是set!print之后可以查看所有参数的默认值。
import numpy as np
np.set_printoptions(precision=4)#precision:设置浮点精度,控制输出的小数点个数,默认是8。
x = np.array([1.145336])
print(x) #[1.1453],注意x是一个只有一个元素的列表!
x = np.arange(50)
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]
np.set_printoptions(threshold=41) #threshold:概略显示,数组中最大值若超过该值,则以“…”的形式来表示,默认是1000。
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]
#———————————————————————————————————————————————#
#小补充:
np.iinfo(np.int8).max #127
np.iinfo(np.int16).max #32767
np.iinfo(np.int32).max #2147483647
np.iinfo(np.int64).max #9223372036854775807
np.finfo(np.float16).max #65500.0
np.finfo(np.float32).max #3.4028235e+38
np.finfo(np.float64).max #1.7976931348623157e+308
#1.没有int4,int128,float8,float128
#2.int必须与np.iinfo()匹配,float必须与np.finfo()匹配,否则报错!
#———————————————————————————————————————————————#
eps = np.finfo(float).eps #2.220446049250313e-16
x = np.arange(4.) #[0. 1. 2. 3.]
x = x ** 2 #[0. 1. 4. 9.]
x= x**2 - (x + eps) ** 2 #[-4.9304e-32 -4.4409e-16 0.0000e+00 0.0000e+00]
np.set_printoptions(suppress=True) #当suppress=True,表示小数不需要以科学计数法的形式输出,默认是False。
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. ]
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}