简体   繁体   English

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

[英]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.

相关问题 如何在特定列中将一行除以具有相同值的另一行? - How to divide one row by another with same value in a specific column? 如何将一列除以另一列,其中一个数据帧的列值对应于 Python Pandas 中另一个数据帧的列值? - How to divide one column by another where one dataframe's column value corresponds to another dataframe's column's value in Python Pandas? 在Python中将一个df中的每一列划分为另一个df中的每一列 - Divide every column in one df to every column in another df in Python 如何使用 openpyxl 将一个 excel 文件的列值与 Python 中另一个 excel 文件的列值进行比较? - How to compare column values of one excel file to the column values of another excel file in Python using openpyxl? 使用python复制CSV文件的一列并将其添加到另一文件 - Copying one column of a CSV file and adding it to another file using python 将一个数据帧除以另一个数据帧,而不考虑一列 - Divide one dataframe by another disconsidering one column 如何使用python将文件分为几个文件 - How to divide file into several files using python 如何使用Python分段分割文本文件 - How to divide a text file sectionwise using Python 如何在 python 中使用相同的键在不同行中划分具有多个值的列 - How to divide a column with multiple values in different rows with same keys in python 如何使用Python defaultdict将一个值除以另一个? - How can I use a Python defaultdict to divide one value by another?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM