【发布时间】:2016-08-13 17:57:17
【问题描述】:
如果我有多个 csv 文件,每个文件都包含按日期索引的时间序列数据。有没有办法创建一个包含所有数据的单个数据框,索引调整为以前文件中可能没有看到的新日期。例如说我在时间序列 1 中阅读:
03/01/2001 2.984
04/01/2001 3.016
05/01/2001 2.891
08/01/2001 2.527
09/01/2001 2.445
11/01/2001 2.648
12/01/2001 2.803
15/01/2001 2.943
数据框看起来很像上面的数据。但是如果我再读另一个文件说时间序列 2
02/01/2001 24.75
03/01/2001 24.35
04/01/2001 25.1
08/01/2001 23.5
09/01/2001 23.6
10/01/2001 24.5
11/01/2001 24.7
12/01/2001 24.4
您可以看到时间序列 1 具有 05/01/2001 的值,而时间序列 2 没有。时间序列 2 也有 02/01/2001 和 10/01/2001 的数据点。那么有没有办法得到以下结果:
02/01/2001 null 24.75 ..etc
03/01/2001 2.984 24.35 ..etc
04/01/2001 3.016 25.1 ..etc
05/01/2001 2.891 null ..etc
08/01/2001 2.527 23.5 ..etc
09/01/2001 2.445 23.6 ..etc
10/01/2001 null 24.5 ..etc
11/01/2001 2.648 24.7 ..etc
12/01/2001 2.803 24.4 ..etc
15/01/2001 2.943 null ..etc
索引针对新日期进行调整的位置以及没有当天数据的任何时间序列设置为 null 或某个此类值?
到目前为止,我的代码相当基本,我可以遍历一个目录并打开 .csv 文件并将它们准备成一个数据框,但我不知道如何以上述方式将数据框组合在一起。
def getTimeseriesData(DataPath,columnNum,startDate,endDate):
#print('startDate: ',startDate,' endDate: ',endDate)
colNames = ['date']
path = DataPath
print('DataPath: ',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]
#not sure of the next bit
【问题讨论】:
标签: python python-3.x pandas dataframe