繁体   English   中英

如何使用Python在同一文件中将一列除以另一列?

[英]how to divide one column by another in in the same file using Python?

我有一个超过 1000000 行的很长的 file.txt,包含如下两列:

photon  electron
1000     100
1010     122
2000     50
1520     190
....     ....

我想要第三列作为分区:电子/光子在 Python 中怎么可能?

使用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)

结果:

   photon  electron       e/p
0    1000       100  0.100000
1    1010       122  0.120792
2    2000        50  0.025000
3    1520       190  0.125000

没有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)

结果:

photon    electron  e/p      
1000      100       0.1      
1010      122       0.120792 
2000      50        0.025    
1520      190       0.125 

根据需要为 python2 或 python3 格式化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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