在文本文件中添加一列

2024-09-22 10:20:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在网站上搜索过了,但没有找到任何与我的案件有关的具体信息。 我有一个从文本文件创建数组的代码,我只想创建一个与输入文件类似的新文件,但是在右边的列中添加了新数组。我该怎么办?

输入文件示例:

4.00171 2.04336E14 14.31034 0.65049
2.56491 6.89220E13 13.83835 1.05022
1.95019 3.45559E13 13.53852 1.38901

创建数组的代码的一部分:

import numpy as np

dataset = np.genfromtxt(fname='input.dat') 
s=dataset[:,3]
d=1.686/s

我只想将数组d添加到输入文件右侧的列中,并将所有内容保存到一个新的输出文件中。(我使用的是Python2.7)。


Tags: 文件代码importnumpy信息示例网站as
3条回答

通过拆分换行符将文件读入行数组。把线绕过去。在将每一行写入新文件之后,追加“d”数组的下一个元素(加上一个换行符)。

使用numpy.appendnumpy.savetxt函数:

dataset = np.genfromtxt('input.dat')
d = 1.686/dataset[:,3]
d = np.reshape(d, (dataset.shape[0],1))   # adjust dimension of the new array
result = np.append(dataset, d, 1)         # append as last column
np.savetxt('output.txt', result, delimiter=" ", fmt="%s")

output.txt内容如下:

4.00171 2.04336e+14 14.31034 0.65049 2.59189226583
2.56491 6.8922e+13 13.83835 1.05022 1.60537792082
1.95019 3.45559e+13 13.53852 1.38901 1.21381415541

为什么不沿着正确的轴concatenate

问题是变量ds都具有(3,)形状,因此它们更像一个向量而不是一个数组。以下解决问题:

s=dataset[:,3]
d=1.686/s
d=d[:,None]
output = np.concatenate((dataset,d), axis=1)

现在你只需要把你的数据输出回一个文件,你就完成了。。。

np.savetxt('example.txt', output)

相关问题 更多 >