цикл for выполняет первое действие, но не второе - PullRequest
0 голосов
/ 04 февраля 2019

У меня есть цикл 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')

Код выполняет первый цикл, но второй цикл не работает. Почему это происходит?Что не так с моим кодом?

EDIT1:

image

1 Ответ

0 голосов
/ 04 февраля 2019

См. Комментарий ниже

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')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...