【问题标题】:Python Pandas datetime and multiindex issuePython Pandas 日期时间和多索引问题
【发布时间】:2017-04-16 05:18:02
【问题描述】:

我有一个 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 日的列,只留下 2016 年 1 月 12 日的数据。这是我的代码:

# 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,因此 Y-M-D,第二个是 2016-01-12,因此 Y-D-M。为什么日期格式不同?我如何将它们都保留为 Y-M-D?

【问题讨论】:

    标签: python datetime pandas dataframe multi-index


    【解决方案1】:

    这行得通:

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

    【讨论】:

      猜你喜欢
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 2017-08-13
      • 2019-06-22
      • 2021-02-18
      • 2017-01-03
      • 1970-01-01
      相关资源
      最近更新 更多