【问题标题】:Importing multiple excel files into Python, merge and apply filename to a new column将多个excel文件导入Python,合并文件名并将其应用于新列
【发布时间】:2019-08-05 10:27:54
【问题描述】:

我有一个 for 循环,它可以导入目录中的所有 Excel 文件并将它们合并到一个数据框中。但是,我想创建一个新列,其中每一行都采用 Excel 文件的文件名字符串。

这是我的导入和合并代码:

path = os.getcwd()
files = os.listdir(path)

df = pd.DataFrame()
for f in files:
    data = pd.read_excel(f, 'Sheet1', header = None, names = ['col1','col2'])
    df = df.append(data)

例如,如果第一个 Excel 文件名为“file1.xlsx”,我希望该文件中的所有行在col3(一个新列)中都具有值file1.xlsx。如果第二个 Excel 文件名为“file2.xlsx”,我希望该文件中的所有行都具有值file2.xlsx。请注意,Excel 文件没有真正的模式,我只是以这些名称为例。

非常感谢

【问题讨论】:

    标签: python excel pandas dataframe import


    【解决方案1】:

    循环创建新列:

    df = pd.DataFrame()
    for f in files:
        data = pd.read_excel(f, 'Sheet1', header = None, names = ['col1','col2'])
        data['col3'] = f
        df = df.append(data)
    

    列表理解的另一种可能的解决方案:

    dfs = [pd.read_excel(f, 'Sheet1', header = None, names = ['col1','col2']).assign(col3 = f)
            for f in files]
    
     df = pd.concat(dfs)
    

    【讨论】:

      猜你喜欢
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-12
      • 1970-01-01
      相关资源
      最近更新 更多