numpy错题整理05——文件保存,格式转化
文章目录
自我介绍
-
我是深圳大学大三的一名大学生,未来想要从事数据分析的工作
-
开始学习python相关库
-
第一步是学习numpy!!
-
若有错误,欢迎指出
资料来源
- 资料来源:https://github.com/fengdu78/Data-Science-Notes
numpy版本
- ‘1.20.3’
刷题
Q1 保存单个array保存到npy文件
-
Save x into
temp.npy
and load it. -
x = np.arange(10) np.save('temp.npy',x) import os if os.path.exists('temp.npy'): x2 = np.load('temp.npy') print(np.array_equal(x,x2))
Q2 保存多个array到npz文件
-
Save x and y into a single file ‘temp.npz’ and load it.
-
x = np.arange(10) y = np.arrange(10,21) np.savez('temp.npz',x=x,y=y) with np.load('temp.npz') as data: x2 = data['x'] y2 = data['y'] print(np.array_equal(x, x2)) print(np.array_equal(y, y2))
Q3 将一个array保存到txt文件中
-
Save x to ‘temp.txt’ in string format and load it.
-
x = np.arange(10) np.savetxt('temp.txt',x) x2 = np.loadtxt('temp.txt') np.array_equal(x,x2)
Q4 将多个array保存到txt文件中
-
Save
x
,y
, andz
to ‘temp.txt’ in string format line by line, then load it. -
x = np.arange(10) y = np.arange(11, 21) z = np.arange(22, 32) np.savetxt('temp.txt',(x,y,z),fmt = %d) np.loadtxt('temp.txt')
Q5 将array转化为2进制形式再还原
-
Convert
x
into bytes, and load it as array. -
x = np.arange(10) x_byte = x.tobyte() print(x_byte) x2 = frombuffer(x_byte,dtype=x.dtype) np.array_equal(x,x2)
Q6 将list转化为array再还原
-
Convert
a
into an ndarray and then convert it into a list again. -
a = [[1, 2], [3, 4]] x = np.array(a) a2 = x.matrix.tolist() print(a2==a)
Q7 设置np中的输出数字位数
-
Print
x
such that all elements are displayed with precision=1, no suppress. -
x = np.random.uniform(size=[10,100]) print(x) np.set_printoptions(0) print(x)
Q8 十进制转为二进制
-
Convert 12 into a binary number in string format.
-
np.binary_repr(12)
Q9 十进制转任意进制
-
Convert 12 into a hexadecimal number in string format.
-
np.base_repr(12,base=10)
总结
- save保存一个array数组到npy文件,savez保存多个array数组到npz文件,用load导入
- savetxt保存一个或者多个文件到txt文件,用loadtxt导入
- 利用array的tobyte()方法转化为2进制形式,利用frombuffer还原
- array转化成list可以用ndarry.matrix.tolist()方法
- binary_repr将十进制转化为二进制,base_repr转化为任意进制