Python:将逗号分隔数据写入 .csv 文件时出现问题

Python: Issues with writing comma delimited data to a .csv file

目标:

  1. .csv file
  2. 中读取股票价格数据
  3. 重新取样
  4. 最终将输出打印到新的 .csv file,其中 所有列均以逗号分隔。

问题:

目前,该程序可以 1) 读入数据并 2) 对其重新采样,但是当打印到输出 .csv 没有逗号分隔符。 此外,第 header 列 打印在同一行上。

输入数据样本:

*感兴趣的列:第一列(即 date/time)、第二列(买入价)和第四列(卖出价)。

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

还尝试了以下代码,它只打印了第一行,也错过了第一列 header 显示 open, high, low, close 的输出:

with open('filename.csv', 'w') as writeFile:
    writer = csv.writer(writeFile, delimiter=',')
    writer.writerow(data_mid)

Q1.如何修改程序保证输出列为comma delimited?

Q2.如何将第header列打印到同一行顶部文件?

您可以为此使用 data_frame.to_csv()。了解它 here