首页 > 解决方案 > 使用 Numpy Array 遍历 .txt 文件中的时间序列数据

问题描述

我的背景是 VBA 并且对 Python 非常陌生,所以请一开始就原谅我。

我有一个包含时间序列数据的 .txt 文件。

在此处输入图像描述

我的目标是遍历数据并进行简单的比较,例如High - Close等。从 VBA 背景来看,这在 VBA 中对我来说是直截了当的,即(简单来说):

Sub Loop()

    Dim arrTS() As Variant, i As Long

    arrTS = Array("Date", "Time", ..)

    For i = LBound(arrTS, 1) to UBound(arrTS, 1)
        Debug.Print arrTS(i, "High") - arrTS(i, "Close")
    Next i

End Sub

现在我在 python 中拥有的是:

import os
import numpy as np
import urllib.request
import matplotlib.pyplot as plt

#load the .txt file
ES_D1 = np.loadtxt(fname = os.getcwd()+"\ES\D1\ES_10122007_04122019_D1.txt", dtype='str')

#now get the shape
print(ES_D1.shape)

Out: (3025, 8)

谁能推荐最好的方法来逐行迭代这个文件,参考特定的列,而不是迭代每个元素?

就像是:

For i = 0 To 3025
   print(ES_D1[i,4] - ES_D1[i,5])
Next i

标签: pythonarraysnumpy

解决方案


为我读取 csv/tsv 文件的常规方法是:

import os

filename = '...'
filepath = '...'
infile = os.path.join(filepath, filename)

with open(infile) as fin:
    for line in fin:
        parts = line.split('\t')
        # do something with the list "parts"

但在您的情况下,使用 pandas 函数read_csv()可能是更好的方法:

import pandas as pd 

# Control delimiters, rows, column names with read_csv
data = pd.read_csv(infile)

# View the first 5 lines
data.head()

推荐阅读