【发布时间】:2016-08-03 01:10:47
【问题描述】:
我在下面有一些代码将一些时间序列 csv 文件导入数据框,并将数据框的列名更改为具有时间序列日期的列的“日期”,其他列设置为他们来自的文件。到目前为止一切都很好。现在我想读入两个预设日期之间的数据。这是我遇到问题的地方。我无法让代码只返回从 startDate 到 endDate 的数据帧并删除其他数据行。
我对此进行了各种尝试,但无法使过滤器正常工作。请在下面查看我的代码的当前版本:
def getTimeseriesData4(DataPath,columnNum,startDate,endDate):
colNames = ['date']
path = DataPath
filePath = path, "*.csv"
allfiles = glob.glob(os.path.join(path, "*.csv"))
for fname in allfiles:
name = os.path.splitext(fname)[0]
name = os.path.split(name)[1]
colNames.append(name)
dataframes = [pd.read_csv(fname, header=None,usecols=[0,columnNum]) for fname in allfiles]
#this is the part where I am trying to filter out the data I do not need. So dataframes would only have data between the startDate and the endDate
dataframes = dataframes.set_index(['date'])
print(dataframes.loc[startDate:endDate])
timeseriesData = reduce(partial(pd.merge, on=0, how='outer'), dataframes)
timeseriesData.columns=colNames
return timeseriesData
以下是我正在导入的数据示例
date BBG.BBG.AUDEUR.FX BBG.BBG.CADEUR.FX BBG.BBG.CHFEUR.FX \
0 01/01/2001 0.5932 0.7084 0.6588
1 02/01/2001 0.5893 0.7038 0.6576
2 03/01/2001 0.6000 0.7199 0.6610
3 04/01/2001 0.5972 0.7021 0.6563
4 05/01/2001 0.5973 0.6972 0.6532
5 08/01/2001 0.5987 0.7073 0.6562
6 09/01/2001 0.5972 0.7095 0.6565
7 10/01/2001 0.5923 0.7105 0.6548
8 11/01/2001 0.5888 0.7029 0.6512
9 12/01/2001 0.5861 0.7013 0.6494
10 15/01/2001 0.5870 0.7064 0.6492
11 16/01/2001 0.5892 0.7047 0.6497
12 17/01/2001 0.5912 0.7070 0.6507
13 18/01/2001 0.5920 0.7015 0.6544
14 19/01/2001 0.5953 0.7083 0.6535
所以如果我将 startDate 设置为 '02/01/2001' 而 endDate 设置为 '05/01/2001'
代码将返回:
date BBG.BBG.AUDEUR.FX BBG.BBG.CADEUR.FX BBG.BBG.CHFEUR.FX \
0 02/01/2001 0.5893 0.7038 0.6576
1 03/01/2001 0.6000 0.7199 0.6610
2 04/01/2001 0.5972 0.7021 0.6563
3 05/01/2001 0.5973 0.6972 0.6532
因此,代码不会返回从 CSV 文件导入的所有数据,而是返回 startDate 和 endDate 之间的数据。
【问题讨论】:
标签: python csv python-3.x pandas