Numpy 写ndarray,第一行字符串后跟数字矩阵
假设我用np.vstack创建了一个大矩阵,第一行是字符串向量,后面是数字矩阵。如何保存/写入文件?以一种很好的方式排列 简化:Numpy 写ndarray,第一行字符串后跟数字矩阵,numpy,python-3.6,Numpy,Python 3.6,假设我用np.vstack创建了一个大矩阵,第一行是字符串向量,后面是数字矩阵。如何保存/写入文件?以一种很好的方式排列 简化: names = np.array(['NAME_1', 'NAME_2', 'NAME_3']) floats = np.array([ 0.1234 , 0.5678 , 0.9123 ]) # 1) In order to vstack them, do I need to expand dimensions? np.expand_dims(floats,
names = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 , 0.5678 , 0.9123 ])
# 1) In order to vstack them, do I need to expand dimensions?
np.expand_dims(floats, axis=0)
np.expand_dims(names, axis=0)
Output = np.vstack((names,floats)) # so I get the following matrix
NAME_1 NAME_2 NAME_3
0.1234 0.5678 0.9123
# 2) How can a save/print into a file being able to modify the format of the numbers?
# And keep the columns aligned?
# Something like this: (taking into account that I have a lot of columns)
NAME_1 NAME_2 NAME_3
1.23e-1 5.67e-1 9.12e-1
# I tryied with:
np.savetxt('test.txt', Matrix, fmt=' %- 1.8s' , delimiter='\t')
# But I can't change the format of the numbers.
提前谢谢 显然,我在kazemakase的评论之后找到了一个解决方案。对于大型矩阵,它感觉效率很低,但它确实起到了作用:
names = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([[ 0.1234 , 0.5678 , 0.9123 ],
[ 0.1234 , -0.5678 , 0.9123 ]])
with open('test.txt', 'w+') as f:
for i in range(names.shape[0]) :
f.write( '{:^15}'.format(names[i]))
f.write( '{}'.format('\n'))
for i in range(floats.shape[0]) :
for j in range(floats.shape[1]) :
f.write( '{:^ 15.4e}'.format(floats[i,j]))
f.write( '{}'.format('\n'))
给出所需的输出:
NAME_1 NAME_2 NAME_3
1.2340e-01 5.6780e-01 9.1230e-01
1.2340e-01 -5.6780e-01 9.1230e-01
谢谢大家!
savetxt
采用标题
参数
In [3]: header = ' '.join(names)
In [4]: header
Out[4]: 'NAME_1 NAME_2 NAME_3'
In [5]: np.savetxt('test.txt', floats, fmt='%15.4e', header=header)
In [6]: cat test.txt
# NAME_1 NAME_2 NAME_3
1.2340e-01 5.6780e-01 9.1230e-01
1.2340e-01 -5.6780e-01 9.1230e-01
这会将浮动放在右边的列中;标题格式需要调整
如果您选择vstack
路径,则会得到一个字符串数组
In [7]: np.vstack((names, floats))
Out[7]:
array([['NAME_1', 'NAME_2', 'NAME_3'],
['0.1234', '0.5678', '0.9123'],
['0.1234', '-0.5678', '0.9123']],
dtype='<U32')
不要在数组中混合字符串和数字。首先写
名称
,然后用适当的格式写浮动
。如何在第一行后追加矩阵?谢谢用f=Open('test.txt')
打开文件。然后将f
而不是文件名传递到np.savetxt
。调用np.savetxt
两次-一次用于标题
,一次用于浮动
。最后,用f.close()
关闭文件。这并不是我想要的,但我很高兴你找到了一种方法。不要担心效率,除非它变得太慢。(提示:您可以编写f.write('\n')
来生成换行符。无需为此使用format
)谢谢hpaulj!这就是我在使用savetxt时看到的,人们只能将其与%15类型的格式一起使用,因此解决方案似乎是要么在使用vstack之前格式化数字,要么在不使用vstack的情况下使用f.write并逐个元素写入。
fmt = ''.join(['%15.4e']*3)+'\n'
f = open(file, 'wb')
f.write(header); f.write('\nl')
for row in floats:
f.write( fmt % tuple(row))
In [9]: fmt=''.join(['%15.4e']*3)
In [10]: print(fmt%tuple(floats[0]))
1.2340e-01 5.6780e-01 9.1230e-01