【问题标题】:for loop performs first action but not the secondfor 循环执行第一个动作但不执行第二个动作
【发布时间】:2019-06-27 20:00:22
【问题描述】:

我有一个我想要的 for 循环:

1) 用数据制作数据透视表

2)将5分钟数据转换为30分钟数据

我的代码如下:

import numpy as np
import pandas as pd
import os 
import glob 


os.chdir('C:/Users/george/Desktop/testing/output/test')

for filename in os.listdir('C:/Users/george/Desktop/testing/output/test'):
    data = pd.read_csv(filename,skiprows=[0])
    table = pd.pivot_table(data, values='SCADAVALUE',columns=['DUID'],index='SETTLEMENTDATE', aggfunc=np.sum)
    table.to_csv(filename+'pivoted.csv')


my_csv_files = []
for file in os.listdir("C:/Users/george/Desktop/testing/output/test"):
    if file.endswith("*pivoted.csv"):
        table.set_index(table.columns[0])
        table.index = pd.to_datetime(table.index) 
        table_resampled = table.resample('30min',closed='right',label='right').mean() 
        table_resampled = table_resampled.reset_index() 
        table.to_csv(filename+'30min.csv')

代码执行了第一个循环,但第二个循环不起作用。这是为什么?我的代码有什么问题?

编辑1:

【问题讨论】:

  • 这里有什么问题?
  • 为什么我的第二个循环失败了?
  • “不起作用”... 怎么样?结果错误?错误?没有执行?...
  • 你有以“*pivoted.csv”结尾的文件吗?
  • 虽然没有错误,但是没有输出任何文件

标签: python pandas numpy


【解决方案1】:

见下方评论

import numpy as np
import pandas as pd
import os 
import glob 


os.chdir('C:/Users/george/Desktop/testing/output/test')

for filename in os.listdir('C:/Users/george/Desktop/testing/output/test'):
    data = pd.read_csv(filename,skiprows=[0])
    table = pd.pivot_table(data, values='SCADAVALUE',columns=['DUID'],index='SETTLEMENTDATE', aggfunc=np.sum)
    table.to_csv(filename+'pivoted.csv')


my_csv_files = []  # what is this variable for?
for file in os.listdir("C:/Users/george/Desktop/testing/output/test"):
    if file.endswith("*pivoted.csv"):

        # At this point you are not reading the file, but you should.  
        # The 'table' variable is still making reference to the the last iteration
        # of the 'for' loop a few lines above

        # However, better than re-reading the file, you can remove 
        # the second 'for file in...' loop,
        # and just merge the code with the first loop

        table.set_index(table.columns[0])
        table.index = pd.to_datetime(table.index) 
        table_resampled = table.resample('30min',closed='right',label='right').mean() 
        table_resampled = table_resampled.reset_index() 
        table.to_csv(filename+'30min.csv')

【讨论】:

    猜你喜欢
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多