English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
NumPy führt ein einfaches Dateiformat für ndarray-Objekte ein: npy.
npy-Dateien werden verwendet, um die Daten, Graphen, dtype und andere Informationen zu speichern, die für die Rekonstruktion von ndarray erforderlich sind.
Gewöhnliche IO-Funktionen sind:
Die Funktionen load() und save() sind die beiden Hauptfunktionen zum Lesen und Schreiben von Array-Daten in Dateien. Standardmäßig werden die Arrays im nicht-komprimierten Originalbinärfomt in Dateien mit der Erweiterung .npy gespeichert. Die Funktion savetxt() wird verwendet, um mehrere Arrays in eine Datei zu schreiben. Standardmäßig werden die Arrays im nicht-komprimierten Originalbinärfomt in Dateien mit der Erweiterung .npz gespeichert. Die Funktionen loadtxt() und savetxt() verarbeiten normale Textdateien (.txt usw.) Parameter description: We can view the contents of the file: It can be seen that the file is garbled because it is the data after the binary format of Numpy. We can use the load() function to read the data and display it normally: 输出结果为: The numpy.savez() function saves multiple arrays to files with the npz extension. Parameter description: 输出结果为: savetxt() 函数是以简单的文本文件格式存储数据,对应的使用 loadtxt() 函数来获取数据。 参数 delimiter 可以指定各种分隔符、针对特定列的转换器函数、需要跳过的行数等。 输出结果为: 使用 delimiter 参数:numpy.save()
numpy.save(file, arr, allow_pickle=True, fix_imports=True)
import numpy as np
a = np.array([1,2,3,4,5]
# Save to test.npy file
np.save('test.npy',a)
# Save to test1.npy file, if the file path does not end with an extension name .npy, the extension name will be automatically added
np.save('test1.npy',a)
$ cat test.npy
?NUMPYv{'descr': '<i8', 'fortran_order': False, 'shape': (5,),}
$ cat test1.npy
?NUMPYv{'descr': '<i8', 'fortran_order': False, 'shape': (5,),}
import numpy as np
b = np.load('test.npy')
print (b)
[1 2 3 4 5]
np.savez
numpy.savez(file, *args, **kwds)
import numpy as np
a = np.array([1,2,3],[4,5,6])
b = np.arange(0, 1.0, 0.1)
c = np.sin(b)
# c used keyword parameter sin_array
np.savez("w3codebox.npz", a, b, sin_array = c)
r = np.load("w3codebox.npz)
print(r.files) # View the names of each array
print(r['arr_0']) # Array a
print(r['arr_'])1']) # Array b
print(r['sin_array']) # Array c
['sin_array', 'arr_0', 'arr_']1']
[[1 2 3]
[4 5 6]
[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
[0. 0.09983342 0.19866933 0.29552021 0.38941834 0.47942554
0.56464247 0.64421769 0.71735609 0.78332691]
savetxt()
np.loadtxt(FILENAME, dtype=int, delimiter=' ')
np.savetxt(FILENAME, a, fmt="%d", delimiter=",")
import numpy as np
a = np.array([1,2,3,4,5]
np.savetxt('out.txt', a)
b = np.loadtxt('out.txt')
print(b)
[1. 2. 3. 4. 5.]
import numpy as np
a = np.arange(0,10,0.5).reshape(4,-1)
np.savetxt("out.txt", a, fmt="%d", delimiter=",") # 改为保存为整数,以逗号分隔
b = np.loadtxt("out.txt", delimiter=",") # load 时也要指定为逗号分隔
print(b)
[[0. 0. 1. 1. 2.]
[2. 3. 3. 4. 4.]
[5. 5. 6. 6. 7.]
[7. 8. 8. 9. 9.]]