【问题标题】:Python, pandas loops works only in the last itemPython,熊猫循环仅适用于最后一项
【发布时间】:2019-09-13 09:32:38
【问题描述】:

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

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

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) 

编辑:我添加了列表文件:

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

文件从here下载。

【问题讨论】:

  • 你能粘贴files吗?它看起来怎么样?
  • @vbrises 请查看编辑
  • @Mim:我认识到,在您对to_csv 的调用中,您没有添加路径。该文件是否有可能实际写入另一个目录?你检查过os.getcwd()返回的目录了吗?
  • 如果你想将文件写入与输入文件相同的目录,你可以在to_csv行中将x替换为path_file
  • @jottbe,结果相同

标签: python pandas rstudio


【解决方案1】:

下面的代码对我有用。可能您在当前目录中只有一个下载的 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) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 2016-04-05
    相关资源
    最近更新 更多