首页 > 解决方案 > 从存储在不同文件夹中的所有 csv 文件创建唯一的数据框

问题描述

我有几个文件夹,其中存储了几个 csv 文件。我想使用 Python 中的函数创建一个唯一的文件/数据框。

名为 的文件夹Main_Folder有 3 个子文件夹:Folder from AFolder from BFolder from C。文件夹A包含三个 csv 文件:

同样的其他两个文件夹,B

C

我试过的是

def create_dataframe(nam):
    path = "path/Folder from "+nam+"/"
    files = [f.split('.')[0] for f in listdir(path) if isfile(join(path, f))]

    dataframe={}
    for file in files:
         dataframe[file] = pd.read_csv(path+file+'.csv')

但它似乎不起作用(当我调用函数时没有输出)。我认为我的方法是错误的。我想要的输出将是一个数据框(唯一),其中包含来自不同三个文件夹(A、B 和 C)的所有文件,还有两个额外的列,一个用于 A/B 和 C(即可以告诉我数据集来自哪里from) 和另一个用于文件名。

像这样的东西:

Col1 Col2 Col3 Col4 .... Source  FileName
.. .. .. .. .. .. ..       A    filename1+tast
.. .. .. .. .. .. ..      ..    ..
.. .. .. .. .. .. ..       A    filename3+cat
.. .. .. .. .. .. ..       B    filename1+tast
.. .. .. .. .. .. ..      ..    ..
.. .. .. .. .. .. ..       B    filename3+dog
.. .. .. .. .. .. ..       C    filename+test
.. .. .. .. .. .. ..      ..    ..
.. .. .. .. .. .. ..       C    filename+d

如果您需要更多详细信息或对此有任何疑问,请告诉我。

标签: pythonpandas

解决方案


您的函数不起作用,因为它不返回任何内容。

要组合不同的数据框,您可以使用pd.concat方法。

例如:

def create_dataframe(paths):
    """ Creates combined dataframe from csv files in paths """

    def get_files_in_path(path):
        return [f.split('.')[0] for f in listdir(path) if isfile(join(path, f))]

    dataframes = {
        (path, file): pd.read_csv(path + file + '.csv')
        for path in paths
        for file in get_files_in_path(path)
    }

    df = pd.concat(dataframes, names=['path', 'file', '_'])
    return df

paths = [f"path/Folder from {name}/" for name in ['A', 'B', 'C']]
df = create_dataframe(paths)

您还可以调用df.reset_index(inplace=True)将索引转换为列:


推荐阅读