python - 熊猫:将多个文件加载到数据框中
问题描述
我有六个不同年份的 CSV 文件,我想将它们组合成一个数据框,并适当地标记列标题。
每个原始 CSV 文件看起来像这样(例如 2010.csv)
state,gender,population
FL,m,2161612
FL,f,2661614
TX,m,3153523
TX,f,3453523
...
这是我想最终得到的结构:
state gender population_2010 population_2012 population_2014 .....
FL m 2161612 xxxxxxx xxxxxxx .....
FL f 2661614 xxxxxxx xxxxxxx .....
TX m 3153526 xxxxxxx xxxxxxx .....
TX f 3453523 xxxxxxx xxxxxxx .....
我怎样才能有效地做到这一点?目前我有这个:
df_2010 = pd.read_csv("2010.csv")
df_2012 = pd.read_csv("2012.csv")
...
temp = df_2010.merge(df_2012, on=("state", "gender"), how="outer", suffixes=("_2010", "_2012")
temp1 = temp.merge(df_2014, on=("state", "gender"), how="outer", suffixes=(None, "_2014")
... repeat five more times to get the final dataframe
但我觉得必须有更好的方法。
解决方案
将状态和性别设置为索引后,在轴 1 上尝试 concat
l = ['2010.csv','2012.csv']
out = pd.concat((pd.read_csv(file).set_index(['state','gender'])
.add_suffix(file.split(".")[0]) for file in l),axis=1)
out = out.reset_index() #finally reset the index if needed
请注意,如果您有文件的原始路径,则可能需要替换file.split(".")[0]
为os.path.split
获取不带扩展名的文件名
推荐阅读
- php - PHP 切换语法
- javascript - 如何使用角度删除使用嵌套循环的表行
- excel - VSTS 代理从 Powershell 运行的 Excel 因未知原因而失败
- c++ - 英语到莫尔斯电码转换器
- ruby-on-rails - Rails - Redis::CannotConnectError:在 localhost:6379 上连接到 Redis 时出错(Errno::ECONNREFUSED)
- android - 应用程序存储如何在 android 上工作?
- sql - 使用链接服务器连接时使用 IF ELSE 错误的 SQL 服务器脚本
- java - 将 curl 转换为 Java HttpPost
- performance - React Native Simulator/Emulator 性能低下
- r - 提取存储在使用 purrr 制作的列表中的多个图形并绘制在单个图像中