首页 > 解决方案 > 使用 to_csv 的 for 循环,只循环一次

问题描述

我有一个使用 for 循环读取和清理 csv 文件的脚本,然后结果会将其保存为新的 csv 文件。读取和清理循环对我所有的 csv 文件都很好,直到它到达“to_csv”函数。它似乎只保存第一个 csv 文件,但不是全部。

这是我的脚本

files_directory = 'C:/Users/Downloads/data/raw_data'
raw_files = os.listdir(files_directory)
csv_files = [] 

def clean_df(csv_files):
    for files in raw_files:
      csv_files.append('{}/{}'.format(files_directory,files))

    for file in csv_files:
        df = pd.read_csv(file, parse_dates=True)

        ### Clean leap years and create just one colum with all data
        df = df.dropna(axis=0) #remove row with feb 29
        df1 = df.drop(df.columns[[0,1]], axis = 1) #remove month and day column
        data = pd.Series(df1.values.ravel('A'))
        
        ##Create years dataframe
        year=list(df1)
        a = [np.repeat(yr, 366) for yr in year]
        df3= pd.DataFrame(a)
        years = pd.Series(df3.values.ravel('C'))
        
        ### Create dataframe with D/Y Dataframe
        months = df.drop(df.columns[[2,3,4,5,6,7,8,9,10,11,12,13,14]], axis = 1)
        months = pd.concat([months]*13, ignore_index=True)
        
        ### Create dataframe with M/D/Y 
        timestep = pd.concat(([months, years]), axis=1, join='inner')
        timestep.columns = ['Month', 'Day', 'Year']
        nat = pd.concat([timestep, data], axis=1, join='inner')
        print(nat)
        
        ## Save it to csv
        only_file_name = csv_files[0].split("/")[-1][0:-4]
        nat.to_csv('{}/{}_new.csv'.format(files_directory, only_file_name), index=False, mode='w') #if mode is a then it will copy paste below
        
        return csv_files

clean_df(csv_files)

标签: pythonexport-to-csv

解决方案


这里:

only_file_name = csv_files[0].split("/")[-1][0:-4]

在循环的每次迭代中,您总是使用第一个文件名的修改版本。所以每次,你都会覆盖同一个文件。看起来你应该使用:

only_file_name = file.split("/")[-1][0:-4]

(我也会避免file用作变量名,因为这是 Python 2 中的内置函数。)


推荐阅读