2016-12-01 7 views
0

Ich habe ein Python-Skript. verschiedene Befehle zu importieren, transponiert und Prozessdaten aus einer CSV-Datei Nach dem Ausführen ich mit einem Datenrahmen am Ende, das wie folgt aussieht:Python Pandas Datetime und Multiindex Ausgabe

 PV   PV 
Date 30/11/2016 01/12/2016 
00:30 4   4 
01:00 5   1 
01:30 6   7 
etc 

Was ich will, jetzt ist die Spalte für 30/11/2016 zu entfernen, nur die Daten für 01/12/2016 lassen. Dies ist der Code, den ich habe:

# create MultiIndex.from_arrays from first row of DataFrame first, then remove first row 
# by df.iloc 
df.columns = pd.MultiIndex.from_arrays([df.columns, pd.to_datetime(df.iloc[0])]) 
df = df.iloc[1:] 

# get today's date minus 60 mins. the minus 60 mins will account for the fact that the 
# very last half hourly data slot is produced at the beginning of the next day 
date = dt.datetime.today() - dt.timedelta(minutes=60) 

# convert to correct format: 
date = date.strftime("%d-%m-%Y") 

# Use indexslice to remove unwanted date columns i.e. none that are not for today's 
# date 
idx = pd.IndexSlice 
df = df.loc[:,idx[:,[date]]] 

# drop the second level of the multiindex, which is the level containing the date, which 
# is no longer required 
df.columns = df.columns.droplevel(1) 

Dies funktioniert gut für die ganzen November bis heute, 1. Dezember, als es begann Fehler werfen. Was ich verfolgt habe der erste Abschnitt des Codes dh ist:

# create MultiIndex.from_arrays from first row of DataFrame first, then remove first row 
# by df.iloc 
df.columns = pd.MultiIndex.from_arrays([df.columns, pd.to_datetime(df.iloc[0])]) 

Der Ausgang davon:

 PV   
Date 2016-11-30 2016-01-12 
Date 30/11/2016 01/12/2016 
00:30 4   4 
01:00 5   1 
01:30 6   7 
etc 

Das Problem in dem ersten Satz von eingegebenen Daten, die erste Angabe ist von welches ist 2016-11-30, deshalb YMD, das zweite ist 2016-01-12, deshalb YDM. Warum unterscheiden sich die Datumsformate? Wie würde ich sie beide als Y-M-D behalten?

Antwort

0

Dies funktioniert:

df.columns = pd.MultiIndex.from_arrays([df.columns, pd.to_datetime(df.iloc[0], format='%d/%m/%Y')]) 
Verwandte Themen