【问题标题】:Loop through directory and create data frame遍历目录并创建数据框
【发布时间】:2017-09-07 05:07:11
【问题描述】:

我正在尝试创建一个数据框,然后遍历一个充满 csv 文件的目录并将这些文件添加到数据框中。我正在尝试使用以下代码:

df = []
for dirName, subdirList, fileList in os.walk(rootDir):
    for fname in fileList:
         df = pd.read_csv(fname)

不幸的是,我收到一条错误消息,指出“文件 CIN_2017 不存在”(确实存在)。关于如何将所有这些 csv 文件添加到数据框中的任何见解?那里有一个 .DS_Store,但其他一切都只是一个 csv。谢谢。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以尝试使用glob 来返回文件名的另一个解决方案,然后循环进入列表理解并创建list of DataFrames。最后将它们连接到一个大的df:

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

    同理:

    import glob
    
    files = glob.glob('files/*.csv')
    dfs = []
    for fp in files:
        dfs.append(pd.read_csv(fp))
    
    df = pd.concat(dfs, ignore_index=True)
    

    【讨论】:

      【解决方案2】:
      import os
      import pandas as pd
      
      un_process_file = []
      
      master_frame = pd.DataFrame(columns=['item_sku', 'external_product_id', 'standard_price', 'quantity'])
      for root, dirs, files in os.walk(os.getcwd()):
          for file_path in files:
              if file_path.endswith('.csv'):
                  try:
                      print file_path
                      file_name = os.path.join(root, file_path)
                      file_frames = pd.read_csv(file_name, skiprows=2,
                                                usecols=['item_sku', 'external_product_id', 'standard_price', 'quantity'])
                      master_frame = master_frame.append(file_frames)
                  except:
                      un_process_file.append(file_path)
      master_frame = master_frame.rename(
          columns={'item_sku': 'sku', 'external_product_id': 'asin', 'standard_price': 'price'})
      master_frame = master_frame.drop_duplicates(subset='asin')
      master_frame.to_csv('masterfile.txt', sep='\t')
      if un_process_file:
          print '\nUnable To Process these files\n'
          for files in un_process_file:
              print files
      

      我也有类似的问题。我做了这个解决方案。根据需要修改columns名称

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-01
        • 1970-01-01
        • 2017-10-07
        相关资源
        最近更新 更多