【问题标题】:How to read file paths from a file and create a single combined dataframe?如何从文件中读取文件路径并创建单个组合数据框?
【发布时间】:2020-06-30 21:42:39
【问题描述】:

必填

1- 我在当前目录中有一个 My_XL_list.txt 文件,其中包含不同文件夹中 excel 文件的路径。我想从 My_XL_list.txt 文件中选择第一个路径并制作一个数据框,然后选择 excel 文件的第二个路径并制作另一个数据框,然后附加两个数据框,然后选择第三个所有路径的 .txt 文件中的路径等等。最后,我想为所有这些数据框制作一个主 excel 文件。

我正在尝试类似的方法,但它没有给我所需的结果。它返回给我一个空的 excel 文件。

import glob
import pandas as pd

all_data = pd.DataFrame()
path = "rC://Users//Desktop/Stockexchange Q/files/*.xlsx"

for f in glob.glob(path):
    df = pd.read_excel(f, index=False, sheet_names='FRJ' )
    all_data = all_data.append(df)


all_data.to_excel('All_Merged_Files.xlsx')

【问题讨论】:

    标签: python pandas path


    【解决方案1】:
    • 为了组合多个数据框,为每个文件创建一个数据框,将其添加到列表中,然后使用pd.concat 组合它们
    • list-comprehension 内,剥离\n,过滤带有'GQH' 的文件,并将每个路径转换为pathlib 对象。
    from pathlib import Path
    import pandas as pd
    
    # path to file
    # p = Path('e:/PythonProjects/stack_overflow/My_XL_list.txt')  # update the path to your path
    p = Path.cwd() / 'My_XL_list.txt'  # if the file is in the current working directory
    
    # extract all the file paths from the file
    with p.open('r', encoding='utf-8') as f:
        files = [Path(file.strip()) for file in f.readlines() if 'GQH' in file]
    
    # print(files) if you want
    [WindowsPath('C:/Users/Desktop/Stockexchange Q/files/names/LT GQH lamas.xlsx'),
     WindowsPath('C:/Users/Desktop/Stockexchange Q/files/names/LT1011 GQH abc.xlsx'),
     WindowsPath('C:/Users/Desktop/Stockexchange Q/files/names/LT110011 GQH Bostonx.xlsx'),
     WindowsPath('C:/Users/Desktop/Stockexchange Q/files/numbers/LT GQH AB.xlsx'),
     WindowsPath('C:/Users/Desktop/Stockexchange Q/files/numbers/LT101011 GQH Abbots.xlsx'),
     WindowsPath('C:/Users/Desktop/Stockexchange Q/files/numbers/LT1100011 GQH Boston-g.xlsx'),
     WindowsPath('C:/Users/Desktop/Stockexchange Q/files/Tums/LT GQH AB.xlsx'),
     WindowsPath('C:/Users/Desktop/Stockexchange Q/files/Tums/LT1000111 GQH Abbot-L.xlsx'),
     WindowsPath('C:/Users/Desktop/Stockexchange Q/files/Tums/LT110011 GQH Bostonk.xlsx')]
    
    # create a list of dataframes inside the list-comprehension and concat them together
    df = pd.concat([pd.read_excel(f, index=False, sheet_names='FRJ') for f in files])
    
    # save file
    df.to_excel('GQH_merged.xlsx', index=False)
    

    【讨论】:

    • 谢谢@Trenton McKinney :)
    猜你喜欢
    • 2017-04-13
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多