代码之家  ›  专栏  ›  技术社区  ›  James Adams

如何通过循环将CSV的负载导入不同的python数据帧?

  •  1
  • James Adams  · 技术社区  · 6 年前

    我有很多csv文件。我想创建一个允许我这样做的循环;

        df_20180731 = pd.read_csv('path/cust_20180731.csv')
    

    对于大约36个文件中的每一个。

    我的档案是df_,df_……df_等,基本上是月底前的日期。

    谢谢

    3 回复  |  直到 6 年前
        1
  •  2
  •   caverac    6 年前
    # include here all ids
    files = ['20160131', '20160231']
    
    _g = globals()
    
    for f in files:
        _g['df_{}'.format(f)] = pandas.read_csv('path/cust_{}.csv'.format(f))
    
    
    print(df_20160131)
    
        2
  •  2
  •   Conner devopensource    6 年前

    你可以这样做:

    import glob
    import pandas as pd
    
    datasets = {}
    for file in glob.glob('path/df_*'):
        datasets[file] = pd.read_csv(file)
    
        3
  •  1
  •   dragonLOLz    6 年前
    import os
    import pandas as pd
    
    # get a list of all the files in the directory
    files = os.listdir(<path of the directory containing all the files>)
    
    #iterate over all the files and store it in a dictionary 
    dataframe = {file: pd.read_csv(file)  for file in files}
    
    #if the directory must contain other files, 
    #you can check the file paths with any logic(extension etc.), in that case
    
    
    def logic(fname):
      return  '.csv' in fname
    
    dataframe = {file: pd.read_csv(file)  for file in files if logic(file) }
    #this will create a dictionary of file : dataframe_objects 
    
    I hope it helps