目标:
- 从
.csv file
读取中的股价数据 - 重新采样
- 最后将输出打印到一个新的
.csv file
,从而所有列都以逗号分隔
问题:
目前,该程序可以1(读入数据,2(对其重新采样,但当打印到输出.csv
时,没有逗号分隔符此外,列标题是而不是打印在同一行上。
输入数据样本:
*感兴趣的列:第一列(即日期/时间(、第二列(出价(和第四列(要价(。
20210602 22:02:00,3.07,50,3.086,50
20210602 22:03:00,3.07,50,3.087,50
20210602 22:04:00,3.071,50,3.087,50
20210602 22:04:00,3.071,50,3.088,50
20210602 22:05:00,3.07,50,3.088,50
20210602 22:05:00,3.07,50,3.087,50
20210602 22:06:00,3.071,50,3.087,50
电流输出:
open high low close
Date_time
2021-06-02 22:02:00 3.0790 3.0790 3.0780 3.0780
2021-06-02 22:03:00 3.0785 3.0785 3.0785 3.0785
2021-06-02 22:04:00 3.0790 3.0795 3.0790 3.0795
2021-06-02 22:05:00 3.0790 3.0790 3.0785 3.0785
2021-06-02 22:06:00 3.0790 3.0790 3.0790 3.0790
预期输出:
Date_time,open,high,low,close
2021-06-02 22:02:00,3.0790,3.0790,3.0780,3.0780
2021-06-02 22:03:00,3.0785,3.0785,3.0785,3.0785
2021-06-02 22:04:00,3.0790,3.0795,3.0790,3.0795
2021-06-02 22:05:00,3.0790,3.0790,3.0785,3.0785
2021-06-02 22:06:00,3.0790,3.0790,3.0790,3.0790
程序尝试:
import pandas as pd
import sys
data_frame = pd.read_csv('03-06-21-xngusd.csv',
names=['Date_time', 'Bid', 'Bid qty',
'Ask', 'Ask qty'],
index_col=0, parse_dates=True)
data_frame.head()
# Resample the data into 1 minute increments
data_ask = data_frame['Ask'].resample('1MIN').ohlc()
data_bid = data_frame['Bid'].resample('1MIN').ohlc()
data_mid = (data_ask + data_bid) / 2
data_mid.head()
# Print the new resample data to a .csv file
original_stdout = sys.stdout # Save reference to original standard output
with open('filename.csv', 'w') as f:
sys.stdout = f
print(data_mid)
sys.stdout = original_stdout
还尝试了以下代码,它只打印了第一行,还错过了显示open, high, low, close
输出的第一列标题:
with open('filename.csv', 'w') as writeFile:
writer = csv.writer(writeFile, delimiter=',')
writer.writerow(data_mid)
Q1.如何修改程序以确保输出列为comma delimited
?
Q2。如何将列标题打印到文件顶部的同一行?
您可以为此使用data_frame.to_csv()
。请在此处阅读。