格式化NumPy数组 [英] Formatting a NumPy array
问题描述
我想要这个:
SP,1,2,3
1,1.000000e+00,2.000000e+00,3.000000e+00
2,1.630000e+01,1.990000e+01,1.840000e+01
3,1.630000e+01,1.990000e+01,1.840000e+01
4,1.630000e+01,1.990000e+01,1.840000e+01
我有以下代码:
np.savetxt("Final Array.csv", my_array, fmt="%10.6e", delimiter=',')
它产生:
1.000000e+00,2.000000e+00,3.000000e+00
1.630000e+01,1.990000e+01,1.840000e+01
1.630000e+01,1.990000e+01,1.840000e+01
1.630000e+01,1.990000e+01,1.840000e+01
我已经为最上面的行和最左边的列创建了数组.
I already have the arrays created for the top row and the left column.
如何设置格式,以便在保持数字格式正确的同时仍保留最左边的列,而最上面的行则保持原样?
How do I format this so that I can keep the numbers formatted correctly while still having the left most column, and the top row stay formatted as they are?
我正在使用vstack和hstack将它们组合在一起,但是"SP"也引起了问题,因为它不是浮点数.
I am using vstack and hstack to combine these, but the "SP" is also causing problems because it isn't a float.
我可以格式化它们,将其全部转换为字符串,合并然后保存txt吗?
Could I maybe format them, convert it all to a string, combine and then savetxt?
推荐答案
一个简单的解决方案需要创建一个与my_array
长度相同的临时数组和一个额外的列.
A simple solution requires to create a temporary array with the same length as my_array
and an extra column.
temp = np.empty((my_array.shape[0], my_array.shape[1]+1))
然后,在第一列中填充所需的索引,在最后一列中填充初始数组:
Then, fill the first column with the indices you want, and the last columns with your initial array:
temp[:,1:] = my_array
temp[:,0] = np.arange(1, len(my_array)+1)
要写入标题,必须首先以书面形式打开文件.您仍然可以将文件对象传递给np.savetxt
,只需修改格式字符串,以使第一列写为int
,其他列写为"%10.6e"
:
In order to write the header, you have to open the file in writing first. You can still pass the file object to np.savetxt
, you just have to modify the format string so that your first column is written as int
, the others as "%10.6e"
:
with open('final.csv', 'w') as f:
f.write("SP,1,2,3\n")
np.savetxt(f, temp, fmt="%i,%10.6e,%10.6e,%10.6e",delimiter=",")
一种更具交互性的方式来定义格式字符串,具体取决于my_array
的列数
A more interactive way to define your format string, depending on the number of columns of my_array
is
fmt = ",".join(["%i"] + ["%10.6e"] * my_array.shape[1])
np.savetxt(f, temp, fmt=fmt, delimiter=",")
这篇关于格式化NumPy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!