【问题标题】:Do some math over two columns of a .dat file and save results into a third column对 .dat 文件的两列进行一些数学运算并将结果保存到第三列
【发布时间】:2013-11-15 20:39:06
【问题描述】:

在 python 中,有一个包含两列的 .dat 文件,假设第一列是 [a1, a2, ... an],第二列是 [b1, b2, ... bn],我如何根据 column1 和 column2 的组件进行一些数学运算并保存结果是一个新的column3?例如,使用以下组件制作第三列的最简单方法是什么 [c1, c2, ... c3] 使得 cn = an + bn

我有类似 .dat 的文件

a1 b1

a2 b2

a3 b3

a4 b4

我想制作一个新的

a1 b1 a1+a2

a2 b2 a2+b2

a3 b3 a3+b3

a4 b4 a4+b4

【问题讨论】:

    标签: python csv file-io


    【解决方案1】:
    f1=open(your_file,'r')
    new_file=open("new_text.txt", 'w')
    for line in f1:
        new_list=line.split()
        new_line=[new_list[0],new_list[1],str(int(new_list[0])+int(new_list[1]))]
        write_line= ' '.join(new_line)
        new_file.write("{} \n".format(write_line))
    new_file.close()
    

    【讨论】:

    • 这不会“做一些数学运算”,它只是连接字符串。
    • @abarnert:我刚刚回答了他想要的。他想将每行的两个数字相加并创建一个新列。当然,如果你是这个意思,我忘了放置 int() 或 float。
    • 是的,既然这是他实际询问的部分,那么回答这部分可能很重要。
    • 附带说明,因为您从不关闭文件,所以输出可能最终为空或不完整。
    • @abarnert:是的,没错,但我假设他知道这一点。我认为,对于他的要求,字符串或数字并不重要。他只想将每行的数字相加并创建新列。但是,是的,我真诚地感谢您的回复。
    【解决方案2】:

    要对值进行数学运算,您必须将它们转换为数字。例如:

    with open(inpath) as infile, open(outpath, 'w') as outfile:
        for line in infile:
            a, b = map(float, line.split())
            total = a + b
            outfile.write('{} {} {}\n'.format(a, b, total))
    

    或者:

    import csv
    with open(inpath) as infile, open(outpath, 'w') as out file:
        incsv = csv.reader(infile, delimiter=' ')
        outcsv = csv.writer(outfile, delimiter=' ')
        for row in incsv:
            a, b = map(float, row)
            total = a + b
            outfile.writerow((a, b, total))
    

    【讨论】:

      【解决方案3】:

      使用 pandas 的便捷、灵活的替代方案,只需四行代码即可处理 csv 和所有内容:

      >>> import pandas as p
      >>> df = p.read_csv('C:/code/test.dat', sep=' ', header=None)
      >>> df
         0  1
      0  3  4
      1  5  6
      2  7  8
      3  1  2
      >>> df[2] = df[0] + df[1]
      >>> df
         0  1   2
      0  3  4   7
      1  5  6  11
      2  7  8  15
      3  1  2   3
      >>> df.to_csv('C:/code/out.dat', sep=' ', header=None, index=False)
      >>> 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-17
        • 2019-01-07
        • 2015-08-31
        • 1970-01-01
        • 1970-01-01
        • 2017-06-26
        • 1970-01-01
        • 2017-05-23
        相关资源
        最近更新 更多