首页 > 解决方案 > 合并几个不同大小的熊猫数据框

问题描述

我的数据框如下所示:

    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 行的东西。

标签: pythonpandasdataframe

解决方案


首先通过 append 创建字典列表,然后使用concatwith 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)

推荐阅读