[英]how to divide one column by another in in the same file using Python?
I have a very long file.txt that exceeds 1000000 rows, contains two columns as follows:我有一个超过 1000000 行的很长的 file.txt,包含如下两列:
photon electron
1000 100
1010 122
2000 50
1520 190
.... ....
I want a 3rd column as division: electron / photon how can it possible in Python?我想要第三列作为分区:电子/光子在 Python 中怎么可能?
One option using pandas
:使用pandas
一种选择:
import pandas as pd
with open('file.txt', 'r') as f:
df = pd.read_csv(f, sep='\s+', header=0)
df['e/p'] = df['electron'] / df['photon']
print(df)
result:结果:
photon electron e/p
0 1000 100 0.100000
1 1010 122 0.120792
2 2000 50 0.025000
3 1520 190 0.125000
Same result without pandas
, using standard-library:没有pandas
相同结果,使用标准库:
import csv
d = []
with open('file.txt', 'r') as f:
data = list(csv.reader(f, delimiter=' ', skipinitialspace=True))
d += [data[0]]
d[0].append('e/p')
for l in list(data)[1::]:
l.append(round(float(l[1])/float(l[0]), 6))
d.append(l)
for i in d:
print '{:<9} {:<9} {:<9}'.format(*i)
result:结果:
photon electron e/p
1000 100 0.1
1010 122 0.120792
2000 50 0.025
1520 190 0.125
Format as desired for python2 or python3.根据需要为 python2 或 python3 格式化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.