LoginSignup
8
9

More than 5 years have passed since last update.

numpyでカラムごとに異なる桁数でcsv出力する

Last updated at Posted at 2016-11-10

機械学習で計算した予測結果を出力するときには、

  • 二値分類なら0/1で出力したい
  • 確率値なら[0,1]でだいたい小数点以下5桁くらいで出力したい
  • 回帰なら取りうる値のレンジに合わせて適当に指数表記で出したい

といったように出力する値の桁数を調整したいことがあります。

numpyではnumpy.savetxt()にてcsvやtsvを出力できますが、このときにfmtパラメータを指定することで桁数を調整することが可能です。

In [1]: import numpy as np

In [2]: np.savetxt("output.csv", [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]])

In [3]: cat output.csv
1.000000000000000056e-01 2.000000000000000111e-01 2.999999999999999889e-01
4.000000000000000222e-01 5.000000000000000000e-01 5.999999999999999778e-01

In [4]: np.savetxt("output.csv", [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]], fmt="%.5f")

In [5]: cat output.csv
0.10000 0.20000 0.30000
0.40000 0.50000 0.60000

実はこのパラメータはリスト形式で複数指定することができます。fmt=["%.0f", "%.1f", "%.5f"]のようにパラメータを設定した場合、各カラム(各列)ごと指定した桁数で出力されます。

In [6]: np.savetxt("output.csv", [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]], fmt=["%.0f", "%.1f", "%.5f"])

In [7]: cat output.csv
0 0.2 0.30000
0 0.5 0.60000

In [8]: np.savetxt("output.csv", [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]], fmt=["%.0e", "%.1e", "%.5e"])

In [9]: cat output1.csv
1e-01 2.0e-01 3.00000e-01
4e-01 5.0e-01 6.00000e-01

ただし、各カラム指定する場合にはすべてのカラムで指定する必要があり、列数が一致しない場合にはエラーとなります。

In [10]: np.savetxt("output.csv", [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]], fmt=["%.0e", "%.1e"])
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-11-6d7d74124420> in <module>()
----> 1 np.savetxt("output.csv", [[0.1, 0.2, 0.3] ,[0.4, 0.5, 0.6]], fmt=["%.0e", "%.1e"])

[...]

AttributeError: fmt has wrong shape.  ['%.0e', '%.1e']

1カラム目にIDが入っている場合や、説明変数はfloatだけど目的変数はintといった型が違う場合に便利です。

参考

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9