简体   繁体   中英

Add column in ASCII that is calculated from existing column

I have an ascii file that contains two columns. I need to add two more columns. The output textfile should contain those two columns and the original two in brackets separated by comma. Opening the ascii in gedit, my input file looks like this:

1  2
3  4
5  6
7  8

in the end I want it to be like this:

2 6 (1,2)
6 12 (3,4)
10 18 (5,6)
14 24 (7,8)

so that my two new columns are a multiple of two/ three of the original ones. I've only come as far as reading in the file as a pandas dataframe and already was confused

import pandas as pd

df = pd.read_csv("test.txt")
print(df)

       1  2
0      3  4
1      5  6
2      7  8

The pandas dataframe that I want to output to ascii is supposed to have this structure:

     2 6 (1   2)
0    6 12 (3   4)
1    10 18 (5   6)
2    14 24 (7   8)

I don't even know how to start because I completely don't understand the structure etc. Any help is appreciated!

You can read the file without pandas:

we=open('new.txt','w')
with open('read.txt') as f:
    for line in f:
#read a line
         a,b=line.split('\t')
#get two values as string
         c=2*int(a)
         d=3*int(b)
#calculate the other two values
         ### edited
         e = ''.join(("(",str(a),",",str(b),")"))
         print(e)
         ####

         #e=str(tuple(a,b))
         #we.write(str(c)+' '+str(d)+e+'\n'
#write to new file

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM