【问题标题】:Iterate and split excel filenames and save as dataframe in Pandas迭代和拆分 excel 文件名并在 Pandas 中保存为数据框
【发布时间】:2019-10-25 09:34:30
【问题描述】:

假设我有一个包含 excel 文件的文件夹 folder1,它们的文件名共享相同的结构:city, building name and id,我想将它们保存在数据框中,然后保存在 excel 文件中。请注意,我还需要在结果中附加其他文件夹的 excel 文件名。

bj-LG center-101012.xlsx
sh-ABC tower-1010686.xlsx
bj-Jinzhou tower-101018.xlsx
gz-Zijin building-101012.xls
...

我尝试过的第一种方法:

import os
import pandas as pd
from pandas import DataFrame, ExcelWriter

path = os.getcwd()
file = [".".join(f.split(".")[:-1]) for f in os.listdir() if os.path.isfile(f)] #exclude files' extension

city = file.split('-')[0]
projectName = file.split('-')[1]
projectID = file.split('-')[2]
    #print(city)        
df = pd.DataFrame(columns = ['city', 'building name', 'id'])
df['city'] = city
df['building name'] = projectName
df['id'] = projectID    

writer = pd.ExcelWriter("C:/Users/User/Desktop/test.xlsx", engine='xlsxwriter')
df.to_excel(writer, index = False)
writer.save()

问题:

Traceback (most recent call last):

  File "<ipython-input-203-c09878296e72>", line 9, in <module>
    city = file.split('-')[0]

AttributeError: 'list' object has no attribute 'split'

我的第二种方法:

for root, directories, files in os.walk(path):
    #print(root)
    for file in files:
        if file.endswith('.xlsx') or file.endswith('.xls'):
            #print(file)            
            city = file.split('-')[0]
            projectName = file.split('-')[1]
            projectID = file.split('-')[2]
            #print(city)        
    df = pd.DataFrame(columns = ['city', 'building name', 'id'])
    df['city'] = city
    df['building name'] = projectName
    df['id'] = projectID    

    writer = pd.ExcelWriter("C:/Users/User/Desktop/test.xlsx", engine='xlsxwriter')
    df.to_excel(writer, index = False)
    writer.save()

我有一个空的test.xlsx 文件,我怎样才能让它工作?谢谢。

【问题讨论】:

    标签: python excel pandas dataframe append


    【解决方案1】:

    方法 2 接近。

    您需要在 for 循环之前创建数据框。分配变量后,制作变量字典并将其附加到数据框。 使用 glob 查找文件列表可能还有更好的方法,但我只会使用您已经完成的工作。

    df = pd.DataFrame()
    for root, directories, files in os.walk(path):
    
        for file in files:
            if file.endswith('.xlsx') or file.endswith('.xls'):
                #print(file)            
                city = file.split('-')[0]
                projectName = file.split('-')[1]
                projectID = file.split('-')[2]
                #append data inside inner loop
                d = {'city':city, 'building name':projectname, 'id':projectID}
                df.append(d)
    
    
    writer = pd.ExcelWriter("C:/Users/User/Desktop/test.xlsx", engine='xlsxwriter')
    df.to_excel(writer, index = False)
    writer.save()
    

    【讨论】:

    • 谢谢。我认为projectID = file.split('-')[2] 行没有排除像.xls.xlsx 这样的扩展名。我有print(df),结果是空的。
    【解决方案2】:

    这应该可以工作,感谢@Dan Wisner 的使用glob 的提示

    import os
    from glob import glob
    
    fileNames = [os.path.splitext(val)[0] for val in glob('*.xlsx') or glob('*.xls')]
    
    df = pd.DataFrame({'fileNames': fileNames})
    df[['city', 'name', 'id']] = df['fileNames'].str.split('-', n=2, expand=True)
    
    del df['fileNames']
    
    writer = pd.ExcelWriter("C:/Users/User/Desktop/test1.xlsx", engine='xlsxwriter')
    df.to_excel(writer, index = False)
    writer.save()
    

    【讨论】:

      【解决方案3】:

      这会拆分文件扩展名,然后将拆分解压缩到变量中。 创建一个字典,然后将字典附加到数据框。

      files = [
          "bj-LG center-101012.xlsx",
          "sh-ABC tower-1010686.xlsx",
          "bj-Jinzhou tower-101018.xlsx",
          "gz-Zijin building-101012.xls"]
      
      df = pd.DataFrame()
      for file in files:
          filename = file.split(".")[0]
          city, projectName, projectID = filename.split("-")
          d = {'city':city,'projectID':projectID,'projectName':projectName}
      
      
          df = df.append(d,ignore_index=True)
      
      df.to_excel('summary.xlsx')
      

      【讨论】:

        猜你喜欢
        • 2021-03-20
        • 2020-05-08
        • 2017-01-04
        • 1970-01-01
        • 2022-08-12
        • 2016-07-27
        • 1970-01-01
        • 2020-10-27
        • 1970-01-01
        相关资源
        最近更新 更多