>>> a = np.arange(8)
>>> b = np.add.accumulate(a)
>>> c = a + b
>>> f = file("result.npy", "wb")
>>> np.save(f, a) # 顺序将a,b,c保存进文件对象f
>>> np.save(f, b)
>>> np.save(f, c)
>>> f.close()
>>> f = file("result.npy", "rb")
>>> np.load(f) # 顺序从文件对象f中读取内容
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> np.load(f)
array([ 0, 1, 3, 6, 10, 15, 21, 28])
>>> np.load(f)
array([ 0, 2, 5, 9, 14, 20, 27, 35])
转自:
http://www.it165.net/pro/html/201406/15606.html
上一篇中我们简要带过了Numpy的数据持久化,在这一篇中将要具体说明Numpy提供的文件存取功能。Numpy可以将数组保存至二进制文件、文本文件,同时支持将多个数组保存至一个文件中。
1. np.tofile() & np.fromfile()
01.
import
numpy as np
02.
import
os
03.
04.
os.chdir(
"d:\\"
)
05.
a = np.arange(
0
,
12
)
06.
a.reshape(
3
,
4
)
07.
array([[
0
,
1
,
2
,
3
],
08.
[
4
,
5
,
6
,
7
],
09.
[
8
,
9
,
10
,
11
]])
10.
11.
a.tofile(
"a.bin"
) #保存至a.bin
12.
13.
b = np.fromfile(
"a.bin"
, dtype=np.int32) #从文件中加载数组,错误的dtype会导致错误的结果
14.
array([
0
,
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
,
11
])
15.
16.
b.reshape(
3
,
4
)
17.
array([[
0
,
1
,
2
,
3
],
18.
[
4
,
5
,
6
,
7
],
19.
[
8
,
9
,
10
,
11
]])
20.
#读取的数据将为一维数组,需要使用reshape改变其数组结构
2. np.save() & np.load() & np.savez()
load()和save()用Numpy专用的二进制格式保存数据,它们会自动处理元素类型和形状等信息。savez()提供了将多个数组存储至一个文件的能力,调用load()方法返回的对象,可以使用数组名对各个数组进行读取。默认数组名arr_0,arr_1,arr_2......
1.
np.save(
"a.npy"
, a.reshape(
3
,
4
))
2.
c = np.load(
"a.npy"
)
3.
c
4.
array([[
0
,
1
,
2
,
3
],
5.
[
4
,
5
,
6
,
7
],
6.
[
8
,
9
,
10
,
11
]])
多个数组存储至一个文件:
01.
a = np.array([[
1
,
2
,
3
],[
4
,
5
,
6
]])
02.
b = np.arange(
0
,
1.0
,
0.1
)
03.
c = np.sin(b)
04.
np.savez(
"result.npz"
, a, b, sin_arr=c) #使用sin_arr命名数组c
05.
r = np.load(
"result.npz"
) #加载一次即可
06.
r[
"arr_0"
]
07.
array([[
1
,
2
,
3
],
08.
[
4
,
5
,
6
]])
09.
r[
"arr_1"
]
10.
array([
0
. ,
0.1
,
0.2
,
0.3
,
0.4
,
0.5
,
0.6
,
0.7
,
0.8
,
0.9
])
11.
r[
"sin_arr"
]
12.
array([
0
. ,
0.09983342
,
0.19866933
,
0.29552021
,
0.38941834
,
13.
0.47942554
,
0.56464247
,
0.64421769
,
0.71735609
,
0.78332691
])
可以使用解压软件解压缩.npz文件会得到存储的各个数组对应的.npy文件以便进行遍历。
3. savetxt() & loadtxt()
01.
a = np.arange(
0
,
12
,
0.5
).reshape(
4
,-
1
)
02.
a
03.
array([[
0
. ,
0.5
,
1
. ,
1.5
,
2
. ,
2.5
],
04.
[
3
. ,
3.5
,
4
. ,
4.5
,
5
. ,
5.5
],
05.
[
6
. ,
6.5
,
7
. ,
7.5
,
8
. ,
8.5
],
06.
[
9
. ,
9.5
,
10
. ,
10.5
,
11
. ,
11.5
]])
07.
np.savetxt(
"a.txt"
, a)
08.
np.loadtxt(
"a.txt"
)
09.
array([[
0
. ,
0.5
,
1
. ,
1.5
,
2
. ,
2.5
],
10.
[
3
. ,
3.5
,
4
. ,
4.5
,
5
. ,
5.5
],
11.
[
6
. ,
6.5
,
7
. ,
7.5
,
8
. ,
8.5
],
12.
[
9
. ,
9.5
,
10
. ,
10.5
,
11
. ,
11.5
]])
13.
np.savetxt(
"a.txt"
, a, fmt=
"%d"
, delimiter=
","
) #指定存储数据类型为整型,分隔符为,
14.
np.loadtxt(
"a.txt"
, delimiter=
','
) #以,分隔符读取
15.
array([[
0
.,
0
.,
1
.,
1
.,
2
.,
2
.],
16.
[
3
.,
3
.,
4
.,
4
.,
5
.,
5
.],
17.
[
6
.,
6
.,
7
.,
7
.,
8
.,
8
.],
18.
[
9
.,
9
.,
10
.,
10
.,
11
.,
11
.]])