首页 > 解决方案 > 熊猫:将多个文件加载到数据框中

问题描述

我有六个不同年份的 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

但我觉得必须有更好的方法。

标签: pythonpandas

解决方案


将状态和性别设置为索引后,在轴 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获取不带扩展名的文件名


推荐阅读