Python、pandas 循环仅适用于最后一项

Python, pandas loops works only in the last item

编辑:我的道歉:我发现了问题,我正在使用 Rstudio 运行 代码,这搞砸了一些东西,我只是从控制台尝试它并且工作正常

我知道,我在做一些愚蠢的事情,但我不知道自己做错了什么,我构建了这个读取 zip 文件、进行一些转换并编写最终 csv 的脚本,但出于某种原因,只写了最后一个文件 该脚本是完全可重现的,如果您想尝试调试它,源文件位于下面的 link 中。

files = os.listdir(os.curdir)
files = [i for i in files if i.endswith('.zip')]
print(files)
for x in files:
     path_file = os.path.join(curDir ,x)
     print(path_file)
     source = pd.read_csv(path_file,
     skiprows=1,
     usecols=["DISPATCH","1" ,"SETTLEMENTDATE", "RUNNO","INTERVENTION","CASESUBTYPE","SOLUTIONSTATUS","NONPHYSICALLOSSES"],
     dtype=str)

     source.rename(columns={'1': 'version'}, inplace=True)
     source.query('version=="2"')

      ################ Extract UNIT, SETTLEMENTDATE,DUID,INITIALMW AND EXPORT TO CSV
     df_unit=source
     df_unit=df_unit.query('DISPATCH=="DUNIT" or DISPATCH=="TUNIT"')
     #Make first row a header
     df_unit.columns = df_unit.iloc[0]
     df_unit = df_unit[1:]
     #create a conditional column
     df_unit.loc[df_unit['DUNIT'] == 'TUNIT', 'INITIALMW1'] = df_unit['INTERVENTION']
     df_unit.loc[df_unit['DUNIT'] == 'DUNIT', 'INITIALMW1'] = df_unit['INITIALMW']
     df_unit.drop(columns=['RUNNO','2','INTERVENTION','INITIALMW','DISPATCHMODE'],inplace=True)
     df_unit.rename(columns={'INITIALMW1': 'INITIALMW','DUNIT': 'UNIT'}, inplace=True)
     df_unit=df_unit.query('SETTLEMENTDATE!="SETTLEMENTDATE" and INITIALMW !="0"')
     df_unit["INITIALMW"] = pd.to_numeric(df_unit["INITIALMW"])
     df_unit['SETTLEMENTDATE']=pd.to_datetime(df_unit['SETTLEMENTDATE'])
     df_unit.head()
     df_unit.to_csv(x.rsplit('.', 1)[0] + '.csv',float_format="%.4f",
     index=False,date_format='%Y-%m-%dT%H:%M:%S.%fZ',compression='gzip')
     print(path_file) 

EDIT: I added list files:

['PUBLIC_DAILY_201906040000_20190605040502.zip', 'PUBLIC_DAILY_201906050000_20190606040501.zip', 'PUBLIC_DAILY_201907140000_20190715040502.zip']

The files are downloaded from here.

下面的代码对我有用。可能您在当前目录中只有一个已下载的 zip 文件,或者实际上您正在 从不正确的目录 调用 jupyter notebook 或 python 脚本。您可以打印 os.getcwd()。否则,代码没有任何问题。所有 zip 文件都必须位于您通过 python 脚本或 jupyter notebook 获取此代码的同一目录中。

files = os.listdir(os.getcwd())
files = [i for i in files if i.endswith('.zip')]
print(files)
for x in files:
    path_file = os.path.join(os.getcwd() ,x)
    print(path_file)
    ...
    ... 
    df_unit.to_csv(x.rsplit('.', 1)[0] + '.csv',float_format="%.4f",
    index=False,date_format='%Y-%m-%dT%H:%M:%S.%fZ',compression='gzip')
    print(path_file)