Numpy 学习专题(六)—— 输入输出

一、numpy二进制文件

  • np.save(file_dir, array)存储单个数组
outfile = 'E:/wxs/Desktop/1.npy'  # 存储路径
np.random.seed(20201122)
x = np.random.uniform(0, 1, [2, 2])  # 产生带存储的数组
np.save(outfile, x)  # 存
y = np.load(outfile)  # 取
print(y)
  • np.savez(file_dir, array)存储多个数组
outfile = 'E:/wxs/Desktop/10.npz'  # 存储路径
x = np.linspace(0, np.pi, 5)
y = np.sin(x)
z = np.cos(x)
np.savez(outfile, x_d=x, y_d=y, z_d=z)  # 存储多个npy文件在npz文件中

data = np.load(outfile)  # 取
np.set_printoptions(suppress=True)  # 解压npz文件得到里面的npy文件

print(data.files)  
# ['z_d', 'arr_0', 'arr_1']
print(data['x_d'])
# [0.         0.78539816 1.57079633 2.35619449 3.14159265]
print(data['y_d'])
# [0.         0.70710678 1.         0.70710678 0.        ]
print(data['z_d'])
# [ 1.          0.70710678  0.         -0.70710678 -1.        ]

二、文本文件

  • np.savetxt(file_dir, array)存取 txt 文件
​outfile = 'E:/wxs/Desktop/1.txt'  # 存储路径
x = np.arange(0, 10).reshape(2, -1)
np.savetxt(outfile, x, fmt='%.4e')  # 保留4位小数
y = np.loadtxt(outfile)  # 取
print(y)
# [[0. 1. 2. 3. 4.]
#  [5. 6. 7. 8. 9.]]
  • np.savetxt(file_dir, array, fmt='%.3f', delimiter=',')存取 csv 文件
​outfile = 'E:/wxs/Desktop/1.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]]
  • csv文件 行、列 读取
outfile = 'E:/wxs/Desktop/1.csv'

x = np.loadtxt(outfile, delimiter=',', skiprows=0)  # 从csv文件的第0行开始读取
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]]

x = np.loadtxt(outfile, delimiter=',', skiprows=0, usecols=(1, 2))  # 使用第1、2列数据
print(x)
#  [[0.5 1. ]
#  [3.  3.5]
#  [5.5 6. ]
#  [8.  8.5]]

val1, val2 = np.loadtxt(outfile, delimiter=',', skiprows=0, usecols=(1, 2), unpack=True)  # 将第1、2列数据分别读取到两个数组
print(val1)  # [1.  3.5 6.  8.5]
print(val2)  # [0.5 3.  5.5 8. ]

补充函数

  • numpy.set_printoptions(precision=None,threshold=None, edgeitems=None,linewidth=None, suppress=None, nanstr=None, infstr=None,formatter=None, sign=None, floatmode=None, **kwarg)
◾precision:设置浮点精度,控制输出的小数点个数,默认是8。
◾threshold:概略显示,超过该值则以“…”的形式来表示,默认是1000。
◾linewidth:用于确定每行多少字符数后插入换行符,默认为75。
◾suppress:当suppress=True,表示小数不需要以科学计数法的形式输出,默认是False。
◾nanstr:浮点非数字的字符串表示形式,默认nan。
◾infstr:浮点无穷大的字符串表示形式,默认inf。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值