python - 使用 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)
解决方案
这里:
only_file_name = csv_files[0].split("/")[-1][0:-4]
在循环的每次迭代中,您总是使用第一个文件名的修改版本。所以每次,你都会覆盖同一个文件。看起来你应该使用:
only_file_name = file.split("/")[-1][0:-4]
(我也会避免file
用作变量名,因为这是 Python 2 中的内置函数。)
推荐阅读
- sqoop2 - sqoop2 作业运行错误,表 'api_open_platform.input_data' 不存在
- node.js - nodejs中的错误“Cast to Number failed for value "undefined" at path 有什么解决方案”
- php - 如何在 PHP List 的 1 值中设置依赖于 List 的 2 值和相反的值
- azure-active-directory - Azure AD:为服务主体授予 appRoleAssignment 失败并出现“代码”:“Request_ResourceNotFound”
- machine-learning - 是否需要测试数据集?
- ios - 如何在CoreData中保存旋转图像并显示旋转图像?
- c# - 如何在富文本框中加载文本?
- java - Spring Boot 战争在外部 tomcat 中出现异常
- php - Docker PHP 容器抛出 200 和 404
- intellij-idea - 查找给定符号的 MMT Unicode 缩写(例如给定☞,查找“juri”)