Python读取第一和第二行,然后读取第二行和第三行

时间:2020-09-30 03:42:21

标签: python python-3.x

我有一个像这样的文件:

截止日期价格

t 101

t + 1 103.1

t + 2 104

t + 3 100

我想计算day(t + 1),day(t + 2),day(t + 3)...的回报率

with open(file, 'r') as f:
    for line1, line2 in f:
        rate_return = (line2[Closed_Price] - line1[Closed_Price])/line1[Closed_Price]
    the next iteration should be line2, line3

有人可以帮助我吗?非常感谢

3 个答案:

答案 0 :(得分:0)

您可以尝试类似的简单操作,其中迭代器为2。

with open(file, 'r') as f:
    f_lst = f.read().splitlines()
    
    for idx in range(0,len(s), 2):
        line1 = f_lst[idx] 
        line2 = f_lst[idx+1]
        rate_return = (line2[Closed_Price] - line1[Closed_Price])/line1[Closed_Price]

答案 1 :(得分:0)

一种解决方案是为for循环的下一次迭代存储当前行。在每次迭代中,您都可以访问上一行当前行。在第一次迭代的情况下,没有存储任何前一行,因此我们跳过了需要两行的操作(在if语句内)。

filename = "lines.txt"

with open(filename, 'r') as file:
    previous_line = None
    for line in file:
        # strip trailing \r\n carriage return and newline character for this line
        line = line.rstrip()
        
        # skip the first line, as there is no previous line
        if previous_line is not None:
            print(previous_line, line, float(line) - float(previous_line))
            
        # store the current line into a variable, to use on the next iteration
        previous_line = line    

带有文件lines.txt

101
103.1
104
100

控制台输出为:

101 103.1 2.0999999999999943
103.1 104 0.9000000000000057
104 100 -4.0

注意:尴尬的小数是由于floating point arithmetic precision引起的;您的计算可能仍然相对准确。

答案 2 :(得分:0)

如果这是CSV文件,则可以将其读取到pandas数据框中,并使用内置函数在其中进行所有分析

import pandas as pd
data = pd.read_csv(file, sep=" ")
data['return'] = data['Closed_Price'].pct_change()