numpy——输入和输出

二进制

npy格式

save函数保存一个数组

import numpy as np
import os
os.chdir(r'C:\Users\15755\Desktop')
outfile = r'.\test.npy'
np.random.seed(20200619)
x = np.random.uniform(0, 1, [3, 5])
np.save(outfile, x)
y = np.load(outfile)
print(y)

在这里插入图片描述
在桌面保存了一个npy的二进制文件,ndim、dtype、shape等信息都被存储了下来,内容是

[[0.01123594 0.66790705 0.50212171 0.7230908  0.61668256]
 [0.00668332 0.1234096  0.96092409 0.67925305 0.38596837]
 [0.72342998 0.26258324 0.24318845 0.98795012 0.77370715]]

savez函数保存多个数组

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)
print(data.files)
print(data['arr_0'])
print(data['arr_1'])
print(data['z_d'])
['z_d', 'arr_0', 'arr_1']
[0.         0.78539816 1.57079633 2.35619449 3.14159265]
[0.         0.70710678 1.         0.70710678 0.        ]
[ 1.          0.70710678  0.         -0.70710678 -1.        ]

在这里插入图片描述
用解压软件打开 test.npz 文件,会发现其中有三个文件: arr_0.npy,arr_1.npy,z_d.npy ,其中分别保存着数组 x,y,z 的内容。

文本文件

savetxt储存txt

outfile = r'.\test.txt'
x = np.arange(0, 10).reshape(2, 5)
np.savetxt(outfile, x)
y = np.loadtxt(outfile)
[[0. 1. 2. 3. 4.]
 [5. 6. 7. 8. 9.]]

在这里插入图片描述

savetxt储存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]]

在这里插入图片描述

格式选项

precision :设置浮点精度,控制输出的小数点个数,默认是8。
threshold :概略显示,超过该值则以“…”的形式来表示,默认是1000。
linewidth :用于确定每行多少字符数后插入换行符,默认为75。
suppress :当 suppress=True ,表示小数不需要以科学计数法的形式输出,默认是False。
nanstr :浮点非数字的字符串表示形式,默认 nan 。
infstr :浮点无穷大的字符串表示形式,默认 inf 。

作业

如何在numpy数组中只打印小数点后三位?

np.set_printoptions(precision=3)
print(np.random.random([5, 3]))

如何限制numpy数组输出中打印的项目数?

a = np.arange(15)
print(a)
np.set_printoptions(threshold=6)
print(a)
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
[ 0  1  2 ... 12 13 14]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值