2016-12-01 16 views
0

私はPythonスクリプトを持っています。 、私が今欲しい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の列を削除することです:CSVファイルからデータをインポート転置およびプロセスに様々なコマンドを実行した後、私はこのようになりますデータフレームで終わります2016年1月12日のデータのみを残します。それがエラーを投げ始めたとき、これは、今日、12月1日まで、11月の全体の罰金働いていた

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

:これは私が持っているコードです。

# 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、2番目は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')])