DataWale_numpy组队学习下-输入和输出
#numpy输入输出
平常对于数据的输入输出用pandas多一些,这一次接触numpy的输入输出另有收获。
numpy 二进制文件
numpy可以用于保存为二进制的文件,在平常的工作中,在进行深度学习模型训练的过程中,我有使用过numpy保存相应的中间数据,但是当时只用到了save()。通过本部分的学习了解到了可以使用save(), savez()保存不同的数据。
save() , 多用于保存单个数组,保存的格式为.npy
import numpy as np
output_file = r'.\test.npy'
np.random.seed(42)
a = np.random.uniform(0, 1, [2, 4])
print(a)
print("*"*50)
np.save(output_file, a)
b = np.load(output_file)
print(b)
#[[0.37454012 0.95071431 0.73199394 0.59865848]
# [0.15601864 0.15599452 0.05808361 0.86617615]]
#**************************************************
#[[0.37454012 0.95071431 0.73199394 0.59865848]
# [0.15601864 0.15599452 0.05808361 0.86617615]]
savez(),可以保存多个数组,并可以为数组命名,如果不命名的话会默认arr_0, arr_1, … 保存的格式为.npz
output_file = r'\test.npz'
np.random.seed(42)
x = np.linspace(0, 10, 5)
y = np.sin(x)
z = np.cos(x)
np.savez(output_file, x=x, y=y, z=z)
tmp_data = np.load(output_file)
np.set_printoptions(suppress=True)
print(tmp_data.files)
#['x', 'y', 'z']
output_file = r'\test.npz'
np.random.seed(42)
x = np.linspace(0, 10, 5)
y = np.sin(x)
z = np.cos(x)
np.savez(output_file, x, y, z)
tmp_data = np.load(output_file)
np.set_printoptions(suppress=True)
print(tmp_data.files)
#['arr_0', 'arr_1', 'arr_2']
文本文件
savetxt(), loadtxt()和genfromtxt() 用来存储和读取文本文件
处理txt文件
1)只打印或显示numpy数组rand_arr的小数点后3位
rand_arr = np.random.random([5, 3])
rand_arr = np.random.random([5, 3])
np.savetxt('.\test.txt', rand_arr, fmt='%.3f')
np.loadtxt('.\test.txt')
#array([[0.183, 0.304, 0.525],
# [0.432, 0.291, 0.612],
# [0.139, 0.292, 0.366],
# [0.456, 0.785, 0.2 ],
# [0.514, 0.592, 0.046]])
处理csv文件
input_file = r'data.csv'
x = np.loadtxt(input_file, delimiter=',', skiprows=1)
print(x)
#[[ 1. 123. 1.4 23. ]
# [ 2. 110. 0.5 18. ]
# [ 3. 164. 2.1 19. ]]
文本格式选项
np.set_printoptions() 设置文本格式
np.set_printoptions(threshold=20)
x = np.arange(50)
print(x)
#[ 0 1 2 ... 47 48 49]
np.iinfo(np.int)
# iinfo(min=-9223372036854775808, max=9223372036854775807, dtype=int64)
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]