使用Numpy数组遍历.txt文件中的时间序列数据

2024-10-04 03:19:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我的背景是VBA,对Python非常陌生,所以请原谅我

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

enter image description here

我的目标是循环遍历数据并进行简单的比较,例如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

Tags: 文件数据importtxtforcloseesas
2条回答

创建简单的for循环比我想象的要容易,这里对其他人来说

import os
import numpy as np
import urllib.requests
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 need to loop through the array
#this is the engine
for i in range(ES_D1.shape[0]):
    if ES_D1[i,3] > ES_D1[i,6]:
        print(ES_D1[i,0])

我阅读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()

相关问题 更多 >