【问题标题】:How to merge several dataframes from a folder into a single dataframe?如何将文件夹中的多个数据框合并为一个数据框?
【发布时间】:2017-08-18 20:17:03
【问题描述】:

我有一个 csv 文件文件夹,每个文件都有一个如下所示的数据框。以下是其中两个数据框的示例:

df1 & df2:

Name     Level
Meg      1
Ben      2
Andy     3
Vern     4
Oscar    5

Name     Level
Hanna    1
Ron      2
Sal      3

这是我目前在文件夹中读取数据帧的代码:

def match_folder(folderpath, exportfile):
    vals = []
    directory = os.fsencode(folderpath)
    os.chdir(directory)
    for file in os.listdir(directory):
        filename = os.fsdecode(file)
        if filename.endswith(".csv"):
            df1 = pd.read_csv(filename)
            vals.append(df1)

不太确定在此之后我会做什么。

我希望最终输出是:

Name     Level
Meg      1
Ben      2
Andy     3
Vern     4
Oscar    5
Hanna    1
Ron      2
Sal      3

【问题讨论】:

    标签: python-3.x pandas dataframe append concatenation


    【解决方案1】:

    IIUC 我们可以使用pd.concat() 方法:

    import glob
    
    df = pd.concat([pd.read_csv(f) for f in glob.glob('/path/to/*.csv')], ignore_index=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-14
      • 1970-01-01
      • 2018-02-17
      • 1970-01-01
      • 2020-08-26
      • 2021-08-16
      相关资源
      最近更新 更多