在Pandas中,如何将多个CSV文件与未命名的日期索引合并



我有一堆格式相同的文件,请注意第一列没有名称。

USD_EUR USD_JPY USD_GBP USD_AUD USD_CAD USD_CHF USD_HKD
1/1/2000    0.995421063 102.2596058 0.618853275 1.535138364 1.454111089 1.597750348 7.767569182
1/2/2000    0.995421063 102.2596058 0.618853275 1.535138364 1.454111089 1.597750348 7.767569182
1/3/2000    0.991080278 101.8334985 0.619028741 1.520911794 1.444697721 1.589990089 7.792269574
1/4/2000    0.970402717 102.7462397 0.610965551 1.52130034  1.449393498 1.557787482 7.782726832
1/5/2000    0.964506173 103.5300926 0.609953704 1.521315586 1.453028549 1.548996914 7.776716821
1/6/2000    0.962649211 104.6592222 0.606661533 1.523681171 1.452733924 1.546784752 7.782345014

如何将它们全部加载到以日期为索引的数据帧中?这是我所拥有的:

files = glob.glob(f"./Data_Forex/*")
if(ForexCache is None):
ForexCache = []
for file in files:
filename = Path(file).stem 
df_fx = pd.read_csv(f"{file}")
df_fx.iloc[:,0] = df_fx.iloc[:, 0].apply(lambda x: datetime.strptime(x, "%Y-%m-%d"))
df_fx.set_index(df_fx.index, inplace=True)
ForexCache.append(df_fx)
ForexCache = functools.reduce(lambda  left,right: pd.merge(left,right,left_index=True, right_index=True, how='outer'), ForexCache)

结果是一堆有索引日期但没有值的空行,每个文件的所有列都是重复的,所以列没有合并,我做错了什么?

假设你所有的文件都在root_folder中,你可以得到一个包含所有文件内容并按日期排序的DataFrame,方法如下:

import os
import pandas as pd
df = pd.concat([
pd.read_csv(os.path.join(root_folder, filename), delim_whitespace=True, parse_dates=True, dayfirst=True)
for filename in next(os.walk(root_folder))[2]
]).sort_index()

最新更新