teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

2

追記

2020/11/07 01:57

投稿

LouiS0616
LouiS0616

スコア35678

answer CHANGED
@@ -2,4 +2,82 @@
2
2
  註: 1次元・2次元の場合のみ
3
3
 
4
4
  ---
5
- テキスト形式で無くても良いなら[np.save](https://numpy.org/doc/stable/reference/generated/numpy.save.html)が手軽でしょう。
5
+ テキスト形式で無くても良いなら[np.save](https://numpy.org/doc/stable/reference/generated/numpy.save.html)が手軽でしょう。
6
+ ```Python
7
+ np.save(f'{file_name}.npy', ndarray)
8
+ ```
9
+
10
+ 読み込むときも[np.load](https://numpy.org/doc/stable/reference/generated/numpy.load.html#numpy.load)が使えます。
11
+
12
+ 計測
13
+ ---
14
+ 3回ファイル書き出しを行って平均を取ります。
15
+
16
+ **環境**
17
+ ```cmd
18
+ C:...>ver
19
+ Microsoft Windows [Version 10.0.18363.1139]
20
+
21
+ C:...>python --version
22
+ Python 3.7.7
23
+ ```
24
+
25
+ **コード**
26
+ ```Python
27
+ import csv
28
+ import timeit
29
+
30
+ import numpy as np
31
+
32
+
33
+ def func1(file_name, ndarray):
34
+ """aiai8976さんの方法"""
35
+ with open(file_name, 'w') as f:
36
+ writer = csv.writer(f)
37
+ for value in ndarray:
38
+ writer.writerow(value)
39
+
40
+ def func2(file_name, ndarray):
41
+ """Moineau26518805さんの方法"""
42
+ ndarray = "\n".join([",".join([str(n) for n in narray]) for narray in ndarray])
43
+ with open(file_name, 'w') as f:
44
+ f.write(ndarray)
45
+
46
+ def func3(file_name, ndarray):
47
+ """toast-uzさんの方法"""
48
+ sample = np.apply_along_axis(lambda x: f"[{' '.join(x)}]", 2, ndarray.astype(str))
49
+ np.savetxt(file_name, sample, delimiter=',', fmt='%s')
50
+
51
+ def func4(file_name, ndarray):
52
+ """LouiS0616の方法"""
53
+ np.save(f'{file_name}.npy', ndarray)
54
+
55
+
56
+ if __name__ == '__main__':
57
+ ndarray = np.random.randint(0, 256, size=(720, 1080, 3))
58
+ repeat = 3
59
+
60
+ for i, func in enumerate([func1, func2, func3, func4]):
61
+ print(func.__doc__)
62
+ print(
63
+ '\t' +
64
+ '{}回繰り返した結果: {:.3f}秒かかりました。'.format(
65
+ repeat,
66
+ timeit.timeit(lambda: func(f'sample{i}.csv', ndarray), number=repeat)
67
+ )
68
+ )
69
+ ```
70
+
71
+ **結果**
72
+ ||必要秒数(3回)|
73
+ |:--|--:|
74
+ |aiai8976さんの方法|107.394秒|
75
+ |Moineau26518805さんの方法|111.174秒|
76
+ |toast-uzさんの方法|24.352秒|
77
+ |私の方法(np.save)|0.027秒|
78
+
79
+ ---
80
+ 私の方法が高速なのはバイナリファイルを書き出しているからです。
81
+
82
+ バイナリ形式にも欠点はありますが、
83
+ **今回は出力が3次元なのでそもそもCSVの強みを活かせない**と考えます。

1

追記

2020/11/07 01:57

投稿

LouiS0616
LouiS0616

スコア35678

answer CHANGED
@@ -1,1 +1,5 @@
1
- [np.savetxt](https://numpy.org/doc/stable/reference/generated/numpy.savetxt.html)は試してみましたか。delimiterを任意に指定できます。
1
+ [np.savetxt](https://numpy.org/doc/stable/reference/generated/numpy.savetxt.html)は試してみましたか。delimiterを任意に指定できます。
2
+ 註: 1次元・2次元の場合のみ
3
+
4
+ ---
5
+ テキスト形式で無くても良いなら[np.save](https://numpy.org/doc/stable/reference/generated/numpy.save.html)が手軽でしょう。