在文本文件中添加新列 [英] Add a new column in text file

查看:80
本文介绍了在文本文件中添加新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在该网站中进行搜索,但没有发现与我的案子有关的任何内容. 我有一个从文本文件创建数组的代码,我只想创建一个与输入文件类似的新文件,但是在右侧的一列中添加了新数组.我该怎么办?

I have already searched in the site but did not find anything specific for my case. I have a code that creates an array from a text file, and I just want to create a new file like the input one, but with the new array added in a column on the right. How can I do?

输入文件示例:

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

创建数组的一部分代码:

A part of code that creates an array:

import numpy as np

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

我只想将数组d添加到输入文件右侧的一列中,然后将所有内容保存在新的输出文件中. (我使用的是python 2.7).

And I just want to add the array d to a column on the right of the input file and save all in a new output file. (I'm using python 2.7).

推荐答案

为什么concatenate沿着正确的轴不做?

Why not do a concatenate along the proper axis?

问题是变量ds都具有形状(3,),因此比数组更像是向量.以下解决了该问题:

The problem is that your variables d and s both have the shape (3,) and thus are more of a vector than an array. The following solves the problem:

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

现在,您只需要将数据输出回文件中就可以了.

Now you just need to output your data back into a file and you're done...

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

这篇关于在文本文件中添加新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆