【问题标题】:Merging several pandas dataframes with different sizes合并几个不同大小的熊猫数据框
【发布时间】:2018-11-12 15:51:28
【问题描述】:

我的数据框如下所示:

    007538839
0   105586.180
1   105582.910
2   105585.230
3   105576.445
4   105580.016

df1.shape = (69302, 1)

这只有一列名称为“007538839”。我还有其他几个数据框也有这样的一列,但列名和行大小不同。

    007543167
0   39886.620
1   39908.777
2   39886.574
3   39884.340
4   39871.098

df2.shape = (69778, 1)

我想将它们全部合并到一个循环中,如下所示:

import os
base_dir = ''
for root, dirs, files in os.walk(base_dir, topdown=False):
  for name in files:
    if root.count(os.sep) == 3 and name.endswith(".csv"):
       file_path = os.path.join(root, name)
       #merge all files

我的目标是不删除任何行,对于还没有值的行,将分配 NaN。例如,如果我合并 df1 和 df2 我应该得到 69778 行的东西。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    首先通过追加创建字典列表,然后使用concat 和axis=1:

    import os
    dfs = []
    base_dir = ''
    for root, dirs, files in os.walk(base_dir, topdown=False):
      for name in files:
        if root.count(os.sep) == 3 and name.endswith(".csv"):
           file_path = os.path.join(root, name)
           df = pd.read_csv(file_path)
           dfs.append(df)
    
    df = pd.concat(dfs, axis=1)
    

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      • 2016-01-01
      • 1970-01-01
      相关资源
      最近更新 更多