【问题标题】:How to combine a hierarchical date and time index into a single datetime index in Pandas?如何在 Pandas 中将分层日期和时间索引组合成单个日期时间索引?
【发布时间】:2014-11-27 10:29:04
【问题描述】:

假设我有以下数据框:

                     temp
2014-11-20 12:45:00        51
2014-11-20 12:46:00        43
2014-11-20 12:47:00        44
2014-11-21 12:45:00        44
2014-11-21 12:46:00        46
2014-11-21 12:47:00        48
2014-11-22 12:45:00        38
2014-11-22 12:46:00        32
2014-11-22 12:47:00        37

如果你复制上面的并使用pd.read_clipboard()我相信你应该得到一个分层索引(或MultiIndex)

第一个索引是日期,第二个索引是字符串形式的时间。如何将两个索引组合成一个日期时间索引?

(请注意,这与使用 pd.read_csv() parse_dates 选项无关,因为数据帧不是来自 csv 文件,问题是如何处理现有数据帧。)

【问题讨论】:

  • 日期和时间级别,是字符串还是 datetime.date/time 对象?
  • @joris:它们目前是字符串。

标签: python datetime pandas


【解决方案1】:

您可以使用to_datetime 方法将字符串解析为日期时间值。要使用它,我认为最简单的方法是首先将日期和时间字符串连接到单级字符串索引:

In [184]: s
Out[184]:
                     temp
2014-11-20 12:45:00    51
           12:46:00    43
           12:47:00    44
2014-11-21 12:45:00    44
           12:46:00    46
           12:47:00    48
2014-11-22 12:45:00    38
           12:46:00    32
           12:47:00    37

In [187]: s.index = s.index.get_level_values(0).values + ' ' + s.index.get_level_values(1)

In [188]: s.index
Out[188]: Index([u'2014-11-20 12:45:00', u'2014-11-20 12:46:00', ... u'2014-11-22 12:47:00'], dtype='object')

然后您可以使用to_datetime 将字符串转换为日期时间索引:

In [189]: s.index = pd.to_datetime(s.index)

In [190]: s.index
Out[190]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2014-11-20 12:45:00, ..., 2014-11-22 12:47:00]
Length: 9, Freq: None, Timezone: None

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-18
    • 2014-03-07
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 2020-01-16
    相关资源
    最近更新 更多