我有一个包含多个包含外汇定价历史的CSV文件的目录:
hist_EUR_CHF.csv
hist_EUR_JPY.csv
hist_EUR_USD.csv
etc.....
我使用以下脚本将所有csv文件合并到一个文件中:
import pandas as pd
import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
merged = []
for f in files:
filename, ext = os.path.splitext(f)
if ext == '.csv':
read = pd.read_csv(f)
merged.append(read)
result = pd.concat(merged)
result.to_csv('_FX_historical.csv')
组合的csv文件现在包含日期,开放,高,低,关闭:
Date Open High Low Close
2018-01-06 1.2032 1.2106 1.1988 1.2033
2018-01-07 1.2041 1.2067 1.2031 1.2044
2018-01-06 93.9023 94.0105 93.8832 93.9024
2018-01-07 93.9671 93.9934 93.9104 93.9672
我想添加两列来标识数据所代表的FX对。
如何附加文件以添加两列:从列和到列?
我的新文件会显示为:
Date Open High Low Close From To
2018-01-06 1.2032 1.2106 1.1988 1.2033 EUR USD
2018-01-07 1.2041 1.2067 1.2031 1.2044 EUR USD
2018-01-06 93.9023 94.0105 93.8832 93.9024 EUR JPY
2018-01-07 93.9671 93.9934 93.9104 93.9672 EUR JPY
答案 0 :(得分:0)
您可以为第二列做同样的事情
fromP = ['EUR2','EUR2','EUR2','EUR2']
with open('_FX_historical.csv','r') as csvinput:
with open('a2.csv', 'w') as csvoutput:
writer = csv.writer(csvoutput, lineterminator='\n')
reader = csv.reader(csvinput)
all = []
row = next(reader)
row.append('From')
all.append(row)
i=0
for row in reader:
row.append(fromP[i])
all.append(row)
i=i+1
writer.writerows(all)