1.首先生成array數組
import numpy as npa = np.random.rand(5,5)print(a)
結果:
array([[0.17374613, 0.87715267, 0.93111376, 0.53415215, 0.59667207], [0.6865835 , 0.15873242, 0.2842251 , 0.73840834, 0.37163279], [0.06556834, 0.68446787, 0.91136611, 0.82796704, 0.81343561], [0.99336674, 0.22961447, 0.78337783, 0.12448455, 0.04388831], [0.50053951, 0.046609 , 0.98179001, 0.446681 , 0.68448799]])
2.保存至txt
使用numpy.savetxt函數,文檔在這里:
https://docs.scipy.org/doc/numpy-1.14.2/reference/generated/numpy.savetxt.html#numpy.savetxt
np.savetxt('a.txt',a,fmt='%0.8f')#第一個參數是要保存的文件名#第二參數是要保存的array#第三個參數是保存的數據格式,詳見文檔
結果:
3.從txt文件中讀取數據
b=np.loadtxt('a.txt',dtype=np.float32)print(b)
結果:
array([[0.17374612, 0.8771527 , 0.9311138 , 0.53415215, 0.59667206], [0.6865835 , 0.15873241, 0.2842251 , 0.7384083 , 0.37163278], [0.06556834, 0.68446785, 0.9113661 , 0.82796705, 0.8134356 ], [0.9933667 , 0.22961447, 0.7833778 , 0.12448455, 0.04388831], [0.5005395 , 0.046609 , 0.98179 , 0.446681 , 0.684488 ]], dtype=float32)
以上這篇python使用numpy讀取、保存txt數據的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答