python - 使用 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
解决方案
为我读取 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()
推荐阅读
- javascript - 如何将我的 HTML 按钮链接到 JS onclick
- python - 如何在 Pygame 中加载图像?
- python - 如何在 discord.py 中遍历所有成员及其角色
- angular - 错误类型错误:无法读取未定义的属性“订阅”
- r - 为什么我在运行包代码时会收到此数组范围错误?
- amazon-web-services - 用 cloudformation 替换 terraform 部署的 lambda
- c# - 如果基于 Codeeffects 编辑器中的计算,有没有办法编写嵌套?
- javascript - 正确组合具有不同选择器 ID 的 javascript 代码
- vue.js - WebStorm 文件关联系统无法识别文件
- aws-lambda - Lambda 跨部署维护检查点