python - 在 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()
推荐阅读
- javascript - 获取最后一个“订购”号码
- neo4j - Neo4j - “CALL apoc.periodic.iterate('” - 错误
- php - 有没有办法用“内连接”子句连接两个表,然后是多个“左连接”子句
- entity-framework - 从 EF 6 升级到 EF Core
- sql - 如何在 Oracle 中动态选择列?这可能吗?
- javascript - 在 Postman 中有效但在 VS 代码中无效的 HTTP 发布请求
- python-3.6 - 如何从 Odoo CRM 中的 col“WON”获取记录
- javascript - 替代节点脚本中的 eval()
- python - Python:如何生成包含在两个列表中重复的项目的列表
- node.js - 通过节点连接到 MongoDB 后,`find()` 不像 `findOne()` 那样工作