繁体   English   中英

如何在python上的文件中减去两行乘以两行的组?

[英]How can I subtract groups of two by two rows of a file on python?

我想减去一个文件的两个连续行。 例如:

我有一个包含4,000,000行的文件,其数据如下:

    2345  345.67
    2344  245.34
    45678  331.45
    45679  339.32
    7654   109.42
    7655   250.78

所以我想减去两个连续的行(列2),并打印绝对结果,即使结果大于或等于60。减法将是两行乘两行,并打印到列1的第一个值。 ,我希望得到这样的结果:

    2345   100.13
    7654   141.36

我试图在bash中执行此操作,但是速度太慢了,我想在python中执行此操作,但是我不知道该怎么做,因为我是python新手。 如何直接读取文件以及如何使用python模块? 我读过的数据框和Abs可以帮助我,但是,怎么办? 你能指导我吗?

非常感谢。

x = 1

而[$ x -ge 2]

a = sed -n '1,2p' file.dat| awk 'NR>1{print $1-p} {p=$1}' sed -n '1,2p' file.dat| awk 'NR>1{print $1-p} {p=$1}'

echo $ a >> results.dat

grep -v“ $ a” file.dat> file.o

mv file.o file.dat

做完了


实际上,您可以将结果直接从Python内部写入文件中。 例如这样的:

# import regular expression module of python
import re
# open file (replace data.txt with input file name and out.txt with the output file name)
with open('data.txt', 'r') as f, open('out.txt', 'w') as o:
    # read the first line (i=0) manually
    currentLine = re.findall('\d+\.?\d*', f.readline())
    # index i starts with 0 and refers to the currentLine, s.t.
    # prevLine
    # currentLine [i=0]
    # prevLine [i=0]
    # currentLine [i=1]
    # therefore we only look at every second iteration
    for i,line in enumerate(f.readlines()):
        # set the previous line to the current line
        prevLine = currentLine
        # extract numbers
        currentLine = re.findall('\d+\.?\d*', line)
        if i%2==0: # look only at every second iteration (row 1 - row 2; row 3 - row 4; etc.)
            # calculate the absolute difference between rows i and i+1, i.e. abs((i,0)-(i+1,1))
            sub = abs(float(prevLine[1])-float(currentLine[1]))
            # if this absolute difference is >= 60, print the result
            if sub>=60:
                outputLine = "%s %s"%(str(prevLine[0]), str(sub))
                print(outputLine)
                o.write(outputLine+"\n") # write the line to the file 'out.txt'

因此,数据输出将是:

2345 100.33000000000001
7654 141.36

暂无
暂无

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

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