conta's diary

思ったこと、やったことを書いてます。 twitter: @conta_

numpy.arrayをテキスト出力

c++からnumpyで作成したデータを読みたかったのでテキスト出力をつくる。

今回は

array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

みたいな配列を

3 3
0 1 2
3 4 5
6 7 8

のような形でtext出力するものをつくる。

numpy.savetxtという関数が便利そうなのでつかってみる。

A = numpy.arange(9).reshape(3,3)
numpy.savetxt('test.txt', A)

結果。

0.000000000000000000e+00 1.000000000000000000e+00 2.000000000000000000e+00
3.000000000000000000e+00 4.000000000000000000e+00 5.000000000000000000e+00
6.000000000000000000e+00 7.000000000000000000e+00 8.000000000000000000e+00   

なるほど。


ヘッダーとフッターを付ける機能があるみたいなので付けてみる。

header = '{0} {1}'.format(A.shape[0], A.shape[1])
numpy.savetxt('test.txt', A, header=header)

結果

# 3 3
0.000000000000000000e+00 1.000000000000000000e+00 2.000000000000000000e+00
3.000000000000000000e+00 4.000000000000000000e+00 5.000000000000000000e+00
6.000000000000000000e+00 7.000000000000000000e+00 8.000000000000000000e+00  


ほう、コメントついちゃう感じか。オプションのところにこう書いてあった。

comments : str, optional
String that will be prepended to the header and footer strings, to mark them as comments. Default: ‘# ‘, as expected by e.g. numpy.loadtxt. .. versionadded:: 1.7.0

commentsオプションをいじって

header = '{0} {1}'.format(A.shape[0], A.shape[1])
numpy.savetxt('test.txt', A, header=header, comments='')

結果

3 3
0.000000000000000000e+00 1.000000000000000000e+00 2.000000000000000000e+00
3.000000000000000000e+00 4.000000000000000000e+00 5.000000000000000000e+00
6.000000000000000000e+00 7.000000000000000000e+00 8.000000000000000000e+00  


めでたしめでたし。
もっといじれば任意のフォーマットで出せるね!

*参考
http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html#numpy.savetxt