簡體   English   中英

使用to_csv的for循環僅循環一次

[英]for loop using to_csv, is only looping once

我有一個腳本,該腳本使用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) 

這里:

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

在循環的每次迭代中,您始終使用第一個文件名的修改版本。 因此,每次都寫入相同的文件。 似乎您應該使用:

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

(我也避免使用file作為變量名,因為它是Python 2中的內置函數。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM