添加根据现有列计算的 ASCII 格式的列
Add column in ASCII that is calculated from existing column
我有一个包含两列的 ascii 文件。我需要再添加两列。输出文本文件应包含这两列和括号中用逗号分隔的原始两列。在 gedit 中打开 ascii,我的输入文件如下所示:
1 2
3 4
5 6
7 8
最后我希望它是这样的:
2 6 (1,2)
6 12 (3,4)
10 18 (5,6)
14 24 (7,8)
所以我的两个新列是原始列的二/三的倍数。我只是将文件作为 pandas 数据框读取,并且已经感到困惑
import pandas as pd
df = pd.read_csv("test.txt")
print(df)
1 2
0 3 4
1 5 6
2 7 8
我要输出为 ascii 的 pandas 数据帧应该具有以下结构:
2 6 (1 2)
0 6 12 (3 4)
1 10 18 (5 6)
2 14 24 (7 8)
我什至不知道如何开始,因为我完全不了解结构等等。感谢任何帮助!
您可以在没有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
希望对您有所帮助
我有一个包含两列的 ascii 文件。我需要再添加两列。输出文本文件应包含这两列和括号中用逗号分隔的原始两列。在 gedit 中打开 ascii,我的输入文件如下所示:
1 2
3 4
5 6
7 8
最后我希望它是这样的:
2 6 (1,2)
6 12 (3,4)
10 18 (5,6)
14 24 (7,8)
所以我的两个新列是原始列的二/三的倍数。我只是将文件作为 pandas 数据框读取,并且已经感到困惑
import pandas as pd
df = pd.read_csv("test.txt")
print(df)
1 2
0 3 4
1 5 6
2 7 8
我要输出为 ascii 的 pandas 数据帧应该具有以下结构:
2 6 (1 2)
0 6 12 (3 4)
1 10 18 (5 6)
2 14 24 (7 8)
我什至不知道如何开始,因为我完全不了解结构等等。感谢任何帮助!
您可以在没有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
希望对您有所帮助