numpy错题整理05——文件保存,格式转化

这篇博客主要整理了numpy中关于数组的保存和格式转换的相关知识点,包括将单个和多个array保存到npy与npz文件,将array写入txt文件,以及数组与二进制之间的转化。此外,还涉及了numpy中设置数字显示精度和十进制转换为二进制及十六进制的方法。适合numpy初学者和准备数据分析工作的人士阅读。
摘要由CSDN通过智能技术生成

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, and z 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)
    

总结

  1. save保存一个array数组到npy文件,savez保存多个array数组到npz文件,用load导入
  2. savetxt保存一个或者多个文件到txt文件,用loadtxt导入
  3. 利用array的tobyte()方法转化为2进制形式,利用frombuffer还原
  4. array转化成list可以用ndarry.matrix.tolist()方法
  5. binary_repr将十进制转化为二进制,base_repr转化为任意进制
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值