2016-12-01 136 views
0

我有一個Python腳本。運行各種命令導入,CSV文件中置和處理數據後,我結束了一個數據幀,看起來像這樣:Python Pandas datetime和multiindex問題

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

我現在要的是刪除列30/11/2016,僅留下2016年12月1日的數據。這是我的代碼:

# 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) 

這是整個十一月的做工精細直到今天,12月1日,當它開始嘔吐起來的錯誤。我一直追溯到它的代碼,即第一部分:

# 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])]) 

的輸出是:

 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 

的問題是在第一盤上面顯示的日期,第一這是2016-11-30,因此YMD,第二個是2016-01-12,因此YDM。爲什麼日期格式不同?我將如何讓他們都成爲Y-M-D?

回答

0

這工作:

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