(1)np.save()和np.load()
#存儲數組數據, .npy文件
import numpy as np
import os
os.chdir(r'C:\python數據分析')
ar = np.random.rand(5,5)
print(ar)
np.save('arraytest.npy',ar)#如果文件路徑末尾沒有擴展名.npy,該擴展名會被自動加上。
#也可以直接np.save(r'C:\python數據分析\arraytest.npy',ar)
#讀取數組數據, .npy文件
ar_load = np.load('arraytest.npy')
print(ar_load) #也可以直接np.load(r'C:\python數據分析\arraytest.npy')
(2)np.savez()和np.load()
ar1 = np.random.rand(2,3)
ar2 = np.arange(4)
np.savez(r'C:\python數據分析\arraytest1.npz',ar1,ar2)
r = np.load(r'C:\python數據分析\arraytest1.npz')
print(r) print(r['arr_0'])
(3)np.savetxt()和np.loadtxt()
ar1 = np.random.rand(2,3)
np.savetxt(r'C:\python數據分析\arraytest2.txt',ar1,delimiter=',') #寫入的時候指定逗號分割,則讀取的時候也要指定逗號分割
ar1_load = np.loadtxt(r'C:\python數據分析\arraytest2.txt',delimiter=',')#指定逗號分割符
print(ar1_load) print(ar1_load.dtype)
#.csv格式 ar1 = np.random.rand(2,3)
np.savetxt(r'C:\python數據分析\arraytest2.csv',ar1,delimiter=',')#csv一定時逗號分隔符
ar1 = np.random.rand(2,3)
np.savetxt(r'C:\python數據分析\arraytest2.txt',ar1,fmt='%.2f')#使用默認分割符(空格),保留兩位小數
print(ar1)
ar1_load = np.loadtxt(r'C:\python數據分析\arraytest2.txt')
print(ar1_load)
print(ar1_load.dtype)