我有一个numpy
数组:
prob_rf = [[0.4, 0.4, 0.4],
[0.5, 0.5, 0.5],
[0.6, 0.6, 0.6]]
我想为每个内部数组添加一个索引号:
prob_rf = [[1, 0.4, 0.4, 0.4],
[2, 0.5, 0.5, 0.5],
[3, 0.6, 0.6, 0.6]]
然后使用csv
将此数组保存到numpy.savetxt
文件中。
我目前正在这样做:
id = [i for i in xrange(1,len(prob)+1)]
prob_rf = np.insert(prob_rf, 0, id, axis=1)
np.savetxt("foo.csv", prob_rf, delimiter=",", fmt='%1.1f')
但这是输出
[[1.0, 0.4, 0.4, 0.4],
[2.0, 0.5, 0.5, 0.5],
[3.0, 0.6, 0.6, 0.6]]
有人可以告诉我如何获得输出
[[1, 0.4, 0.4, 0.4],
[2, 0.5, 0.5, 0.5],
[3, 0.6, 0.6, 0.6]]
答案 0 :(得分:7)
使用带有fmt
参数的列表指定每列的格式:
fmt=['%d', '%1.1f', '%1.1f', '%1.1f']
完整示例:
import numpy as np
prob_rf = [[1, 0.4, 0.4, 0.4],
[2, 0.5, 0.5, 0.5],
[3, 0.6, 0.6, 0.6]]
np.savetxt("foo.csv", prob_rf, delimiter=",", fmt=['%d', '%1.1f', '%1.1f', '%1.1f'])
生成的文件:
1,0.4,0.4,0.4
2,0.5,0.5,0.5
3,0.6,0.6,0.6