簡體   English   中英

Python Pandas日期時間和多索引問題

[英]Python Pandas datetime and multiindex issue

我有一個Python腳本。 運行各種命令以從CSV文件導入,轉置和處理數據后,我得到的數據框如下所示:

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

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

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

在整個11月,直到今天,即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。 為什么日期格式不同? 我如何將它們都保留為YMD?

這有效:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM